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!
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!