bagrut1
bagrut1

Reputation: 41

Simulating rolling two dice java and see if the results are `1,1`

This is my homework problem, in Java: Write a program that simulates rolling 2 dice 20 times. The program outputs each pair of results and computes and outputs the number of times the result was 1, 1.

I've tried to run this code, but I'm running into issues. This is my code:

Scanner in = new Scanner(System.in);
int dice1, dice2, i, j, countOneOne;
countOneOne = 0;
// dice1 = 0;
// dice2 = 0;

for (j = 1;j <= 5; j++) {
    dice1 = 1 +(int) (Math.random() * 6); 
    j = dice1;
    System.out.println("Result of dice1: " + dice1);
} 
for (i = 1; i <= 5; i++) {
    dice2 = 1 +(int)(Math.random()*6);
    i = dice2;
    System.out.println("Result of dice2: " + dice2);
}

System.out.println("Result of dice1: " + dice1 + " ; Result of dice2: " + die2);   

if (dice1 == 1 && dice2 == 1) countOneOne++;

System.out.println(countOneOne + " is the number of 1, 1 results");

Firstly, it keeps telling me that I have to initialize dice1 and dice2 and I don't understand why. But more importantly, I know that this can't be correct, but I'm just not sure how to write a code that simultaneously rolls the two dice and then counts when they are both 1 at the same time.

Also, I tried to put them both in the same for a loop. Is this possible?

Upvotes: 4

Views: 1377

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Your code is off a little bit, when using Math.random() * 6 you will get a value in the range 0 to 5 inclusive (you need to add one). Also, the logic is much simpler if you extract the logic for rolling a die to a method. Something like,

public static int rollDie(int sides) {
    return (int) (Math.random() * sides) + 1;
}

Then you want to implement your method. Loop twenty times, roll two die. Count the number of snake eyes and print the roll results. Like,

public static void main(String[] args) throws Exception {
    int snakeEyes = 0;
    // Twenty times
    for (int i = 0; i < 20; i++) {
        // Roll two dice
        int die1 = rollDie(6), die2 = rollDie(6);

        // Count snake eyes.
        if (die1 == 1 && die2 == 1) {
            snakeEyes++;
        }

        // Display roll results.
        System.out.printf("Result of die1: %d ; Result of die2: %d%n", die1, die2);
    }
    System.out.printf("%d is the number of 1,1 results%n", snakeEyes);
}

Upvotes: 6

Related Questions