C. Mills C. Mills - 2 months ago 10
Java Question

How to loop a println statement?

I'm making a dice rolling program that prompts the user to enter the number of times a die should be rolled, and using a loop print out the random die roll as many times as the user inputs.

So what I did so far was make a variable for timesRolled and set up a do while that would add "+1" to the times rolled every time it would loop and then while numberOfRolls (userInput) is greater than timesRolled (the value that is looping +1) it is supposed to keep printing out a random roll.

System.out.println("Enter the number of times a 6 sided die " +
"should\nbe rolled");
Random r = new Random();
int numberOfRolls = userInput.nextInt();
int randomRoll = r.nextInt(6) +1;
int timesRolled = 0;

if (numberOfRolls <=0)
{
System.out.println("Nope, that's below zero");
System.exit(0);
}
do
{
timesRolled ++;
}
while (numberOfRolls < timesRolled);
System.out.println(randomRoll+ " was rolled");
}


BUT, all it does is output the random roll once and not loop like I want it to:


Enter the number of times a 6 sided die should be rolled


User input: 10

5 was rolled

Process finished

Answer

The do statement should be:

do
{
    timesRolled ++;
    System.out.println(randomRoll+ " was rolled");
}
while (numberOfRolls < timesRolled);