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

Write a program using JAVA and named GuessingGame Using a random numner generato

ID: 3811328 • Letter: W

Question

Write a program using JAVA and named GuessingGame

Using a random numner generator, a while loop and a sentineal value. Guess a number between 1-20.

Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “That is too high – Guess again”. If the user’s guess is lower than the random number, the program should display “That is too low – Guess again”. If the user guesses correctly, “Congrats! You nailed it!”, is displayed to the user. The program should use a loop that repeats until the user correctly guesses the random number.

Keep track of the number of guesses that the user makes.

Include a sentinel value (of -1), so that the user may exit from the guessing game at any time.

Explanation / Answer

GuessingGame.java

package a2;

import java.util.Random;
import java.util.Scanner;

public class GuessingGame {
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       Random r = new Random();
       int randNum = r.nextInt(20)+1;
       System.out.println("Enter your guess(-1 to quit): ");
       int guess = scan.nextInt();
       int tries = 0;
       while(guess != randNum && guess != -1){
           tries++;
           if(guess < randNum){
               System.out.println("That is too low – Guess again");
           }
           else {
               System.out.println("That is too high – Guess again");
           }
           System.out.println("Enter your guess(-1 to quit): ");
           guess = scan.nextInt();
          
       }
       if(guess != -1){
           System.out.println("Congrats! You nailed it!");
           System.out.println("Number of tries: "+tries);
       }
       System.out.println("Thanks for playing");
   }
}

Output:

Enter your guess(-1 to quit):
15
That is too high – Guess again
Enter your guess(-1 to quit):
10
That is too high – Guess again
Enter your guess(-1 to quit):
1
That is too low – Guess again
Enter your guess(-1 to quit):
5
That is too low – Guess again
Enter your guess(-1 to quit):
8
That is too high – Guess again
Enter your guess(-1 to quit):
7
Congrats! You nailed it!
Number of tries: 5
Thanks for playing

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote