Build a number guessing game that combines while loops, conditionals, and user input. The program picks a random number between and , and the player keeps guessing until they find it.
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random();
int secret = rand.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
int guess = 0;
int attempts = 0;
while (guess != secret) {
System.out.print("Guess a number (1-100): ");
guess = scanner.nextInt();
attempts++;
if (guess < secret) {
System.out.println("Too low!");
} else if (guess > secret) {
System.out.println("Too high!");
}
}
System.out.println("Correct! It took " + attempts + " guesses.");
scanner.close();
}
}
Notice that the while loop is the right choice here. You don't know how many guesses the player will need. The loop condition guess != secret keeps the game running until they get it right.