(26 pts) Write a simple guessing game that works like this: 1 and n, inclusive.
ID: 3909416 • Letter: #
Question
(26 pts) Write a simple guessing game that works like this: 1 and n, inclusive. At the beginning of the checking loop to ensure The computer randomly produces an integer between . game, the player should be able to enter a value for n. that n is at least 1. ncludean error The player repeatedly guesses integers until s/he gets the number correct. ° Each time the player enters a guess, the computer tells him/her whether the guess is too high, too low, or the correct number. If the player's guess is outside the range 1-n, the computer shows an error message (but the player can continue entering guesses afterward) . Once the player gets the correct number, the computer reports the number of guesses that it took However, guesses that are outside the range 1-n should not be included in this count. Example program run: (the underlined parts indicate what you type in as the program is running) Let's determine how difficult to make this guessing game! t My random integer should range from l to what? You must enter at least 1. My random integer should range from 1 to what? 10 OK, let's go! I am thinking of an integer between 1 and 10. Enter your guess: 5 Too high! Enter your guess: -1 Hey, that's totally out of bounds! 2 Enter your guesS: 3 Too high! Enter your guess: Too low! Enter your guess: You got it, congrats! It only took you this many tries: 4Explanation / Answer
here is your program : --------->>>>>>>>>
import java.util.Random;
import java.util.Scanner;
public class GuessGame{
public static void main(String[] args) {
int low = 1;
int high = 1;
int guess = 0;
int secret = 0;
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.println("Let's determine how difficult to make this guessing game!");
while(true){
System.out.println("My random integer should range from 1 to what?");
high = sc.nextInt();
if(high < 1){
System.out.println("You must enter at least 1.");
}else{
System.out.println("Ok, let's go!");
break;
}
}
System.out.println("I am thinking of an integer between "+low+" and "+high+".");
secret = rand.nextInt((high - low) + 1) + low;
int n = 0;
while(true){
n++;
System.out.println("Enter your guess : ");
guess = sc.nextInt();
if(guess < 1 || guess > high){
System.out.println("Hey, that's totally out of bounds!");
}else if(guess < secret){
System.out.println("Too low!");
}else if(guess > secret){
System.out.println("Too high!");
}else if(guess == secret){
System.out.println("You got it, congrats!");
System.out.println("It only took you this many tries : "+n);
break;
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.