1

I am new to Java and writing code. I want to program a simple board game. But if I roll the dice, I get the same number every roll. What did I do wrong?

I have a class to create a random between 1 and 6:

public class Dice {
    public int throwDice() {
        Random random = new Random();
        int dice = random.nextInt(6) + 1;
        return dice;
    }
}

And the main class:

public class BoardGame{

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String r;
        Dice dice = new Dice();
        int roll = dice.throwDice();
        int position = 0;
        int finish = 40;

        while (finish >= position) {
            do {
                System.out.print("Roll the dice (r): ");
                r = input.nextLine();
            } while (!r.toLowerCase().equals("r"));

            if (r.toLowerCase().equals("r")) {
                System.out.println("You have rolled " + roll + ".");
                position += roll;
                System.out.println("You are now on square " + position + ".");
            }

        }
        System.out.println("You won!");
        input.close();
    }

}

Thank you!

4 Answers4

2

The code that does get a random result:

int roll = dice.throwDice();

runs exactly once. You call the throw method once. You store the result, not a "pointer" to a function that would get invoked repeatedly whenever roll gets used somewhere.

So you should put that line:

roll = dice.throwDice();
System.out.println("You have rolled " + roll + ".");

right in front of the place where you expect another roll of the dice!

achAmháin
  • 4,176
  • 4
  • 17
  • 40
GhostCat
  • 137,827
  • 25
  • 176
  • 248
1
public class Dice {
    private Random random;
    public Dice(){
        random = new Random();
    }

    public int throwDice(){
        int dice = random.nextInt(6) + 1;
        return dice;
    }
}

This will work because your Dice now has one random instance which is generating new random integers everytime throwDice() is called

david
  • 11
  • 1
0

Change your Dice class to this.

public class Dice {
    private Random random;
    public Dice(){
        random = new Random();
    }

    public int throwDice(){
        int dice = random.nextInt(6) + 1;
        return dice;
    }
}

And update roll = dice.throwDice(); inside the loop. This will work because your Dice now has one random instance which is generating new random integers everytime throwDice() is called.

exilour
  • 516
  • 5
  • 12
0

After you add int roll = dice.throwDice(); to your loop you may find that you get the same sequence of roles each time. If you do not want that you will have to set the random seed.

See this question: Java random numbers using a seed

jerlich
  • 340
  • 3
  • 12