Guess a hidden number between 1 and 1000. The program uses a do-while loop to keep the iteration going until the user gets the correct number.
Description: Guess a hidden number between 1 and 1000. The program uses a do-while loop to keep the iteration going until the user gets the correct number. The program gives the user a "higher/lower" hint after each guess.
Code
package asu.numberguessinggame;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
Scanner keyboard = new Scanner(System.in);
int guess;
do {
System.out.println("Enter a guess (1-1000): ");
guess = keyboard.nextInt();
if (guess == secretNumber)
System.out.println("Your guess is correct. Congratulations!");
else if (guess < secretNumber)
System.out.println("Your guess is smaller than the secret number.");
else if (guess > secretNumber)
System.out.println("Your guess is greater than the secret number.");
} while (guess != secretNumber);
}
}
Output
Enter a guess (1-1000):
500
Your guess is greater than the secret number.
Enter a guess (1-1000):
250
Your guess is smaller than the secret number.
Enter a guess (1-1000):
325
Your guess is smaller than the secret number.
Enter a guess (1-1000):
400
Your guess is smaller than the secret number.
Enter a guess (1-1000):
450
Your guess is smaller than the secret number.
Enter a guess (1-1000):
475
Your guess is greater than the secret number.
Enter a guess (1-1000):
457
Your guess is greater than the secret number.
Enter a guess (1-1000):
453
Your guess is smaller than the secret number.
Enter a guess (1-1000):
455
Your guess is smaller than the secret number.
Enter a guess (1-1000):
456
Your guess is correct. Congratulations!