Solution to your problem
while(running){
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber) {
System.out.println("You are correct");
break;
}
else if (guess > randomNumber){
System.out.println("Too high.");
}
else if (guess < randomNumber){
System.out.println("Too low");
}
else {
System.out.println("Try again");
}
}
Becomes
do {
System.out.println("Guess your number");
guess = scan.nextInt();
if(guess == randomNumber) {
System.out.println("You are correct");
break;
}
else if (guess > randomNumber){
System.out.println("Too high.");
}
else if (guess < randomNumber){
System.out.println("Too low");
}
else {
System.out.println("Try again");
}
}
while(running);
The Difference
In a while loop
, the code can run 0-*
times. (0 to many). In a do-while
loop, the code can run 1-*
times.
Stack overflow ethos
Try to think of this place as more of a last resort. I googled do while loop java
and the first link was this which explains your issue perfectly. In future, perhaps you should use your own methods of research before you rely on ours.
Edit for you
A for loop
is different, in that it will run x
times. Like so:
for(int x = 0; x < 5; x++)
{
System.out.println("Hello " + x);
}
/**
* OUTPUT:
* Hello 0
* Hello 1
* Hello 2
* Hello 3
* Hello 4
*/
Applying While loops to your problem
The do-while
loop has a conditional statement in it, inside the while
.
do {
}
while(something is true)
Think of that as your if statement
. Now you want that to be true, until the person has guessed 12
times. It only logically follows that you want to keep count of the number of guesses, so we’ll introduce an int
called guesses
. And you only want guesses
to reach 12
and no more, so this is where we’ll go from.
do {
// Some code goes here.
guesses ++;
// Increase the number of guesses if they got it wrong.
}
while(correct = false && guesses < 12)
What I’ve done is made up a variable called correct
, that tells if the person got it right or not. And I increase the value in guesses
each time they make a guess that’s wrong. That means the loop will only stop if:
- The person guesses correctly
- The person had 12 attempts