While Loops (JAVA) Create a game where the player must guess a random number tha
ID: 3675473 • Letter: W
Question
While Loops (JAVA)
Create a game where the player must guess a random number that is generated by the computer. You will need to decide the range of numbers that your program will use. Be sure to tell the user what that range is so that they can make a valid first guess. You will need to modify the getRandomNumber() code to reflect your range. Remember that nextInt( n ), where n is some value, returns a value from 0 (inclusive) up to n (exclusive). After the user enters a guess, tell them if their answer was correct, too low or too high. The program should loop until the user enters the correct value. After the user answers correctly, display a count of the number of attempts that it took. Save the file as RandomGuess.java.
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
/**
* @author srinu
*
*/
public class RandomGuess {
public static void main(String[] args) {
int secretNumber, min, max;
Scanner keyboard = new Scanner(System.in);
secretNumber = (int) (Math.random() * 999 + 1);
System.out.print("Enter the min range:");
min = keyboard.nextInt();
System.out.print("Enter the max range:");
max = keyboard.nextInt();
secretNumber = getRandomNumber(min, max);
System.out.println("Secret number is " + secretNumber); // to be removed
// later
int guess;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
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);
}
/**
*
* random number between min and max
*
* @param min
* @param max
* @return
*/
public static int getRandomNumber(int min, int max) {
Random random = new Random();
int randomNumber = random.nextInt(max - min) + min;
return randomNumber;
}
}
OUTPUT:
Enter the min range:10
Enter the max range:100
Secret number is 69
Enter a guess: 75
Your guess is 75
Your guess is greater than the secret number.
Enter a guess: 23
Your guess is 23
Your guess is smaller than the secret number.
Enter a guess: 60
Your guess is 60
Your guess is smaller than the secret number.
Enter a guess: 68
Your guess is 68
Your guess is smaller than the secret number.
Enter a guess: 75
Your guess is 75
Your guess is greater than the secret number.
Enter a guess: 69
Your guess is 69
Your guess is correct. Congratulations!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.