Java: Calculate number of do/while loop
So I've made this guessing game where you the computer randomly picks a number between 1-100 and the user have to guess the correct number. I've made that working, now I want to calculate how many times the loop has repeated itself if you may say, or well how many times the user has "guessed".
This is the current code:
int random = 0;
int a;
random = ((int)(Math.random()*100+1));
System.out.println("Guess the number");
do
{
a = Keyboard.readInt();
if (a > random)
{
System.out.println("Less");
}
if (a == random)
{
System.out.println("Correct");
}
if (a < random)
{
开发者_运维百科System.out.println("More");
}
}
while (a != random);
Use a counter variable:
int guessCount = 0;
do {
guessCount++;
...
} while (...)
At the end of the loop, you can print the guess count.
You could simply add an int guesses = 0;
variable, and increment it at the top of the do
block.
int random = 0,guessed=0;
int a;
random = ((int)(Math.random()*100+1));
System.out.println("Guess the number");
do
{
guessed++;
a = Keyboard.readInt();
if (a > random)
{
System.out.println("Less");
}
if (a == random)
{
System.out.println("Correct");
System.out.println("Guessed" +guessed +"times ";
}
if (a < random)
{
System.out.println("More");
}
}
while (a != random);
精彩评论