Write a program that asks a user to guess a secret number between 1 and N, where
ID: 3790860 • Letter: W
Question
Write a program that asks a user to guess a secret number between 1 and N, where N is a positive number that the user is prompted for. The program should also prompt the user for the maximum number of guesses they would like to make. Each time the player makes a guess, the program shall respond with “correct”, “too low”, or “too high”. The program should keep track of the number of guesses the user made to discover the secret number. The program should continue execution until the user has discovered the secret number or has exceeded the maximum number of guesses.
Explanation / Answer
SecretNumberGame.java
import java.util.Random;
import java.util.Scanner;
public class SecretNumberGame
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int ActualNumber;
System.out.println("Enter a positive number: ");
int n = scan.nextInt();
System.out.println("Enter the maximum number of guesses they would like to make: ");
int numOfGuess = scan.nextInt();
Random r = new Random();
ActualNumber = r.nextInt(n)+1;
Scanner keyboard = new Scanner(System.in);
int guess;
int tries = 0;
System.out.println("Please think of a number between 1 and "+n);
System.out.println();
do {
tries++;
System.out.print("Enter your guess: ");
guess = keyboard.nextInt();
if (guess == ActualNumber)
System.out.println("correct");
else if (guess < ActualNumber)
System.out
.println("too high");
else if (guess > ActualNumber)
System.out
.println("too low");
} while (guess != ActualNumber && tries < numOfGuess);
if (guess != ActualNumber){
System.out.println("You lost!");
}
}
}
Output:
Enter a positive number:
100
Enter the maximum number of guesses they would like to make:
10
Please think of a number between 1 and 100
Enter your guess: 88
too low
Enter your guess: 77
too low
Enter your guess: 66
too low
Enter your guess: 11
too high
Enter your guess: 22
too high
Enter your guess: 44
too high
Enter your guess: 46
too low
Enter your guess: 45
correct
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.