I am working on a simple game in which the user has to guess a random number. I have all the code set up except for that fact that if the guess is too high or too low I don't know how to allow them to re-enter a number and keep playing until they get it. It just stops; here is the code:
import java.util.Scanner;
import java.util.Random;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int random = rand.nextInt(10) + 1;
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
}
}
In order to repeat anything you need a loop.
A common way of repeating until a condition in the middle of loop's body is satisfied is building an infinite loop, and adding a way to break out of it.
Idiomatic way of making an infinite loop in Java is while(true)
:
while (true) {
System.out.print("Pick a number 1-10: ");
int number = input.nextInt();
if (number == random) {
System.out.println("Good!");
break; // This ends the loop
} else if (number > random) {
System.out.println("Too Big");
} else if (number < random) {
System.out.println("Too Small");
}
}
This loop will continue its iterations until the code path reaches the break
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With