tbusse125
tbusse125

Reputation: 25

Dice-rolling program, not outputting what I need

I'm writing a program that simulates the rolling of two 6-sided dice. The program will "reroll" the dice over and over until it achieves a 7. The program keeps track of how many rolls it took to get to 7. At the end of the code, the program will output an average which will be computed by (total number of rolls / n) "n" being the number of times the user chose to select the program.

The new issue I'm having is with the average number of rolls it takes to get a 7. I'm getting averages such as 0.125 rolls which obviously doesn't make any sense. I need to add in a new parameter I would guess but again, not sure.

  import java.util.*;
public class HW9 {
    public static void main(String args []) {
        Scanner s = new Scanner(System.in);
        int n = -1;
        do {
            System.out.println("Enter a number greater than 1.");
            n = s.nextInt();
        }
        while(n <= 1); 
        int total = 0;
            for(int i = 0; i < n; i++) {
            int times = 0;
            int result = 0;
            while(result !=7) {
                result = (1 + ((int)(Math.random()* 6))) + (1 + ((int)(Math.random() * 6)));
                times++;
            }
            total = times;
        }
            System.out.println("Average: " + (double)total/n);
        }
    }

Upvotes: 2

Views: 129

Answers (2)

Simon Poole
Simon Poole

Reputation: 513

Your issue is with your loop condition.

while(n > 1);

It repeats the statements inside your do block, while the condition is true. Inputting a number > 1 means the condition stays true, so it will continue to ask for input until you input a 0 or a negative number.

To fix it you would need to swap the condition statement, like so: while(n < 1)

Upvotes: 1

Jorge
Jorge

Reputation: 560

You are asking for a number greater than 1, but you are repeating your loop everytime the input is a number greater than 1.

do {
        System.out.println("Enter a number greater than 1.");
        n = s.nextInt();
    }
while(n > 1); 

That while(n > 1) should be while(n < 1) or whatever you want to put in there.

Upvotes: 1

Related Questions