Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Printing an Array in Java & a few other questions.

  • 26-03-2010 12:40pm
    #1
    Registered Users, Registered Users 2 Posts: 7,231 ✭✭✭


    WARNING if you are doing this project, dont use this code, it's awful :)

    Basically, I have no idea how to do this, I got three lectures on Java basics at the start of this module but aside from that, I havent been taught Java at all (I got taught processing which is hideously simplified Java with no OOP seemingly, I was just taught how to do things with it, the significance of different things (Like the term/whatever "Void" etc) was never explained. Despite this, I'm expected to complete a project in Java.......

    Basically, it's a dice game. Roll 5 dice and compute the score. I have the bulk of the code done.

    It's done in Eclipse with 3 classes (Dont really understand classes at all but anyway....) and the Stream Class (Not entirely sure, but I was told to have it!)
    
    package gamelogic;
    
    /**
     * This class is used to generate a random number and then output it to the other classes for use.
     */
    
    public class Die 
    {
    	/**
    	 * Member variable to represent the possible values of the face's of dice.
    	 */
    	public int face;
    	/**
    	 * Default constructor
    	 */
    	public Die() {
    		rollDie();
    	}
    	
    	/**
    	 * rollDie() generates random number between 1 & 6 and stores the value in face.
    	 */
    	
    	public void rollDie(){
    		face = ((int)(6*Math.random())+1) ;
    	}
    	
    	/**
    	 * getFace() returns the value of face.
    	 * @return face - the value of the Die's face
    	 */
    	public int getFace(){
    		return face;
    		
    	}
    	
    		
    	}
    
    package gamelogic;
    
    public class Dice {
    
    	/**
    	 * Class variables
    	 */
        int [] scores;
        Die [] DiceArray;
    
        /**
         * Constructor - maybe make a default one too? (This is where I changed things, DiceArray is of type Die)
         * @param NoOfDice
         */
        public Dice(int NoOfDice){
            scores= new int [6];
            DiceArray= new Die[NoOfDice];
            for (int i=0; i<NoOfDice; i++){
                Die temp = new Die();
                DiceArray[i] = temp;
            }
        }
        
        /**
         * rollDie() - Method to roll a die for each element of the DiceArray using the rollDie() method. (This is fine, 
         * we're just rolling a die for each die in the array)
         */
        public void rollDie(){
            for (int i = 0; i < DiceArray.length; i++) {
                DiceArray[i].rollDie(); 
            }
        }
        
        /**
         * evaluateScore() - Method to evaluate the score obtained. (Bit more explanation here about the method you're using
         * to obtain the total score? Not quite clear here)
         * @return score
         */
        public int evaluateScore(){
            int score=0;
            for (int i = 0; i < DiceArray.length; i++) {
                int diceFace = DiceArray[i].getFace();
                     scores[diceFace-1]++;
            }
            
            for (int i = 0; i < scores.length; i++) {
                if (scores[i] == 2){
                    score=10;
                }
                else if (scores[i] == 3){
                    score=75;
                }
                else if (scores[i] == 4){
                    score=200;
                }
                else if (scores[i] == 5) {
                    score=250;
                }
                
            }
            return score;
        }
        
    
        
    }
    

    package gamelogic;
    
    import java.io.IOException;
    import java.lang.reflect.Array;
    import java.util.Scanner;
    
    public class DiceGame {
     
        public static void main(String[] args) throws IOException {
            DiceGame myDiceGame = new DiceGame();
            myDiceGame.runDiceGame();
        }
    
        public void runDiceGame() throws IOException {
            
            System.out.println("*** Welcome To My Dice Game ***");
            String playAgain="Y";
            do{
                Scanner in = new Scanner(System.in);
                
                System.out.println("How Many Dice Would You Like To Play With? (between 1-5? Enter Number Below)");
                int noofdice=in.nextInt();
                Dice myDiceSet = new Dice(noofdice);
                myDiceSet.rollDie();
                //System.out.println(Array.asList(myDiceSet));
    
                // I'd maybe like to see the dice rolled printed out here, even just for debugging purposes. 
                int score=myDiceSet.evaluateScore();
                
                            
                if (score == 10) {
                    
                    System.out.println("Well Done, 2 Of Your Dice Match, Your Score is "+score);
                }
                
                if (score== 75) {
                    
                    System.out.println("Well Done, 3 Of Your Dice Match, Your Score is "+score);
                }
                
                if (score== 200) {
                    
                    System.out.println("Well Done, 4 Of Your Dice Match, Your Score is "+score);
                }
                
                if (score== 250) {
                    
                    System.out.println("Well Done, 5 Of Your Dice Match, Your Score is "+score);
                }
                
                System.out.println("Would You Like To Play Again? Y or N?");
                playAgain=in.next();
            if (playAgain.equals("N")) {
                System.out.println("Okay, Thank You for Playing :)");
                break;
            }
            }while(playAgain=="Y");
            	
        }
    }
           
    
    package gamelogic;
    
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.text.DecimalFormat;
    import java.util.NoSuchElementException;
    import java.util.StringTokenizer;
    
    /* The Stream class     
     *
     * Provides simple input from the keyboard and files.
     * And formatted output to the screen and files.
     *
     * Constructors
     * ------------
     * public Stream (InputStream in)
     * public Stream (String filename, int why)
     *
     * Input
     * -----
     * public int    readInt ()
     * public double readDouble ()
     * public String readString ()
     * public char   readChar ()
     *
     * Output
     * ------
     * public void println  - for Objects, String, int, double, char
     * public void print    - for Objects, String, int, double, char
     * public void close()
     *
     * Output - class methods
     * ----------------------
     * public String format (int number, int align)
     * public String format (double number, int align, int frac)
     */
    
    public class Stream {
      private BufferedReader in;
      private PrintWriter out;
      private StringTokenizer T;
      private String S;
    
      public static final int
    	READ = 0,
    	WRITE = 1;
    
      public Stream(InputStream i) {
    	in = open(i);
      }
    
      public Stream(String filename, int how) throws FileNotFoundException, IOException {
    	switch(how) {
    	  case READ: in = open(filename); break;
    	  case WRITE: out = create(filename); break;
    	}
      }
    
      private BufferedReader open(InputStream in) {
    	return new BufferedReader(new InputStreamReader(in));
      }
    
      private BufferedReader open(String filename) throws FileNotFoundException {
    	return new BufferedReader(new FileReader(filename));
      }
    
      private PrintWriter create(String filename) throws IOException {
    	return new PrintWriter(new FileWriter(filename));
      }
    
      public String readLine () throws IOException {
        refresh();
        return S;
      }
    
      public int readInt () throws IOException, NumberFormatException{
        if (T==null) refresh();
        while (true) {
          try {
            return Integer.parseInt(T.nextToken());
          }
          catch (NoSuchElementException e1) {
            refresh ();
          }
        }
      }
    
      public char readChar () throws IOException, NumberFormatException {
        if (T==null) refresh();
        while (true) {
          try {
            return T.nextToken().trim().charAt(0);
          }
          catch (NoSuchElementException e1) {
            refresh ();
          }
        }
      }
    
      public double readDouble () throws IOException {
        if (T==null) refresh();
        while (true) {
          try {
            String item = T.nextToken();
            return Double.valueOf(item.trim()).doubleValue();
          }
          catch (NoSuchElementException e1) {
            refresh ();
          }
        }
      }
    
      public String readString () throws IOException {
        if (T==null) refresh ();
        while (true) {
          try {
            return T.nextToken();
          }
          catch (NoSuchElementException e1) {
            refresh ();
          }
        }
      }
    
      private void refresh () throws IOException {
        S = in.readLine ();
        if (S==null) throw new EOFException();
        T = new StringTokenizer (S);
      }
    
      private static DecimalFormat N = new DecimalFormat();
      private static final String spaces = "                    ";
    
      public static String format(double number, int align, int frac) {
        N.setGroupingUsed(false);
    	N.setMaximumFractionDigits(frac);
    	N.setMinimumFractionDigits(frac);
    	String num = N.format(number);
    	if (num.length() < align)
    	   num = spaces.substring(0,align-num.length()) + num;
        return num;
      }
    
      public static String format(int number, int align) {
        N.setGroupingUsed(false);
        N.setMaximumFractionDigits(0);
        String num = N.format(number);
        if (num.length() < align)
           num = spaces.substring(0,align-num.length()) + num;
        return num;
      }
    
    	public void println(Object s) {
    		out.println(String.valueOf(s));
    		out.flush();
    	}
    
    	public void println(String s) {
    		out.println(s);
    		out.flush();
    	}
    
    	public void println(int s) {
    		out.println(s);
    		out.flush();
    	}
    
    	public void println(double s) {
    		out.println(s);
    		out.flush();
    	}
    
    	public void println(char s) {
    		out.println(s);
    		out.flush();
    	}
    
    	public void print(Object s) {
    		out.print(String.valueOf(s));
    		out.flush();
    	}
    
    	public void print(String s) {
    		out.print(s);
    		out.flush();
    	}
    
    	public void print(int s) {
    		out.print(s);
    		out.flush();
    	}
    
    	public void print(double s) {
    		out.print(s);
    		out.flush();
    	}
    
    	public void print(char s) {
    		out.print(s);
    		out.flush();
    	}
    
    	public void close() throws IOException {
    		if (out != null)
    			out.close();
    		if (in != null)
    			in.close();
    	}
    
    	public void flush() {
    		out.flush();
    	}
    }
    
    

    Basically, I need help with three things.

    One, getting the array of Die Faces to print (I cannot, for the life of me find something that will allow me to print the array or the elements of the array).

    Two, getting the program to start again if a player hits "Y"

    Three, which I'm really not too pushed about, being able to allow the player to select up to three of the dice and allowing them to roll them again.

    I dont want to be told the answer, I just want to be told how I might be able to do this, what's wrong with the code etc, because I just dont know how to figure this out.

    If this isnt allowed just lock the thread.


Comments

  • Closed Accounts Posts: 414 ✭✭Thomas-G


    I didn't read the code too much but to print the elements in the array:
    for(counter = 0; counter < arrayname.length; cnt++)
    {[INDENT]System.out.println(arrayname[cnt]);
    [/INDENT]}
    
    I don't know how I could explain that without giving the answer....


  • Registered Users, Registered Users 2 Posts: 1,101 ✭✭✭Rulmeq


    Fad wrote: »
    ...snipped code...
    Use Random.nextInt(6) instead of the code you are using (it is liable to fail unpredictably, and will not give you an even distribution of random numbers, for reasons that are too difficult to go into in a simple post.
    Also take a look at the sun coding standards guide (or at least pick one style and stick to it :P )
    http://java.sun.com/docs/codeconv/
    Fad wrote: »
    Basically, I need help with three things.

    One, getting the array of Die Faces to print (I cannot, for the life of me find something that will allow me to print the array or the elements of the array).
    A simple loop as suggested by the previous post, or use one of the built in Java collection classes.
    Fad wrote: »
    Two, getting the program to start again if a player hits "Y"
    For some reason you are using the Scanner class instead of the Stream class that was provided to you, there might be an method provided to help you with this, also you are ignoring the IOException (throwing in the method, and the main method).
    Fad wrote: »
    Three, which I'm really not too pushed about, being able to allow the player to select up to three of the dice and allowing them to roll them again.
    There would be a number of ways to implement this.


  • Registered Users, Registered Users 2 Posts: 7,231 ✭✭✭Fad


    Project submitted, thanks for the help.


  • Closed Accounts Posts: 4,564 ✭✭✭Naikon


    Java should not be the language of choice for first year programming students. That code masks simple concepts behind alot of cruft. Java code tends to send shivers down my spine. @OP- do what you need for your assignments but please offset that Java coding with something else.

    /rant


  • Registered Users, Registered Users 2 Posts: 7,231 ✭✭✭Fad


    Naikon wrote: »
    Java should not be the language of choice for first year programming students. That code masks simple concepts behind alot of cruft. Java code tends to send shivers down my spine. @OP- do what you need for your assignments but please offset that Java coding with something else.

    /rant

    I would have no problem, had I been taught the fúcking language......but NO, CS department decides Java's too had for life scientists/classes for pure CS students were too big.......utter manure imo....but anyway.


  • Advertisement
  • Closed Accounts Posts: 4,564 ✭✭✭Naikon


    Fad wrote: »
    I would have no problem, had I been taught the fúcking language......but NO, CS department decides Java's too had for life scientists/classes for pure CS students were too big.......utter manure imo....but anyway.

    You made a pretty good go at that assignment. Not slating you in any way OP because I know damm well how crappy programming lectures can be in college. I once had to teach myself assembly langauge for
    a Microprocessors module because the Lecturer had too much knowledge but not much Lecturing ability. Still managed 69% overall:pac: It's not a nice concept at all, but sometimes you are going to have to accept
    the Lecturers may not teach to your learning style. Granted, too much self learning is not the solution for everybody as I have witnessed.

    Keep up with it despite the head banging off the wall feelings and you will be flying in no time. Programming is not something you can learn in a short space of time.
    I used to be quite frustrated with programming at first, but it does get alot easier the longer you keep at it. I can't speak for Java though because I don't really use it.


  • Registered Users, Registered Users 2 Posts: 7,231 ✭✭✭Fad


    betafrog wrote: »
    To be fair, the previous years all programming students were lumped together meaning CS students had to learn at the same pace as everybody else and also meant a lot of important concepts weren't being taught and this lead to a lot of hassle down the line.

    Fair better for CS students to be taught programming separately from everyone else. Although I will agree that processing is a load of ****e

    My problem is that I intend on doing CS next year......meaning I need to catch up.

    Meh! I have a long summer, and other than working, I have little to do, so now I have something to work on :)


Advertisement