Programming Examples
Develop a number guessing game where the user has to guess a number between 1 and 100, and the program provides feedback on whether the guess is too high, too low, or correct. Use a do while loop to keep the game running until the correct guess is made
Java Program to Develop a number guessing game where the user has to guess a number between 1 and 100, and the program provides feedback on whether the guess is too high, too low, or correct. Use a do while loop to keep the game running until the correct guess is made.
Solution
import java.util.Scanner;
public class NumberGuessingGame
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Generate a random number between 1 and 100
int targetNumber = 1+(int)(Math.random()*100);
int guess = 0;
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I have selected a number between 1 and 100.");
System.out.println("Can you guess what it is?");
do {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
if (guess < targetNumber) {
System.out.println("Too low! Try again.");
} else if (guess > targetNumber) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You guessed the correct number.");
}
} while (guess != targetNumber);
scanner.close();
}
}
Output
Welcome to the Number Guessing Game!
I have selected a number between 1 and 100.
Can you guess what it is?
Enter your guess: 5
Too low! Try again.
Enter your guess: 10
Too low! Try again.
Enter your guess: 50
Too low! Try again.
Enter your guess: 60
Too low! Try again.
Enter your guess: 80
Too high! Try again.
Enter your guess: 70
Too low! Try again.
Enter your guess: 75
Congratulations! You guessed the correct number.