Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a program that simulates the \"Guess a number\" game. first the program ge

ID: 3629922 • Letter: W

Question

write a program that simulates the "Guess a number" game. first the program generates a random integer between 1 and 100. it then asks the user to enter a guess (between 1 and 100) and reads the user's guess. according to the guess the program prints an appropriate message "too low - try again" or "too high - try again" and repeats doing the above until the user guess the correct number. at the end the program outputs how many guess it took the user to find the correct number.

note: please use loops.

Explanation / Answer

public static void main(String[] args)
{
// setup keyboard input
Scanner kb = new Scanner(System.in);

// generate random integer between 1 and 100
int rand = (int)(Math.random()*100+1);

int guess = 0;
int guesscount = 0;
// ask for guess until it's correct

do
{
System.out.print("Enter your guess: ");
guess = kb.nextInt();
guesscount++;

// check if too high or too low
if(guess < rand)
{
System.out.println("Too low - try again.");
}
else if(guess > rand)
{
System.out.println("Too high - try again.");
}
}
while(guess != rand);

System.out.println("Correct! It took you "+guesscount+" guesses.");
}