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

(( IN JAVA ONLY )) Write a program that plays a guessing game with the user. Spe

ID: 673857 • Letter: #

Question

(( IN JAVA ONLY ))

Write a program that plays a guessing game with the user. Specifically, your program should randomly pick a number between 1 and 100. Then, ask the user for a guess. You should detect and tell the user if the guess is not a valid guess. Otherwise, tell the user their guess was too high or too low. The program should continue to prompt the user for new guesses until they get the correct number, telling them each time if the guess was too high or too low or invalid.

You have been supplied code to pick a random number between 1 and 100 each time you run your program. Here are a couple development/debugging strategies for this “target” variable:

Print out the random number, to make sure your program is acting correctly – remember to remove/comment this before running unit tests/submitting.

Temporarily set the random “seed” to a value, which will have the effect of always choosing the same random number – the unit tests have fixed seeds that you can use with known outcomes.

Temporarily set the “target” variable to a fixed number, so you can test to see how your program responds in different testing situations.

Here’s a sample run of a working version of the program:

Enter your guess (between 1 and 100): 50

Too high!

Enter your guess (between 1 and 100): 0

Invalid guess, try again!

Enter your guess (between 1 and 100): 101

Invalid guess, try again!

Enter your guess (between 1 and 100): 25

Too high!

Enter your guess (between 1 and 100): 12

Too high!

Enter your guess (between 1 and 100): 6

Too high!

Enter your guess (between 1 and 100): 3

Too low!

Enter your guess (between 1 and 100): 4

Too low!

Enter your guess (between 1 and 100): 5

You win!

(( IN JAVA ONLY ))

Explanation / Answer

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

public class GuessingGame{

   public static void main(String args[]){
       Random randomGenerator = new Random();
       Scanner in = new Scanner(System.in);
       int numToGuess = 1 + randomGenerator.nextInt(100);
       int guessNumber;
       do{
       System.out.println("Enter your guess (between 1 and 100):");
       guessNumber = in.nextInt();
       if(guessNumber < 1 || guessNumber > 100)
           System.out.println("Invalid guess, try again!");
       else if(guessNumber == numToGuess)  
           System.out.println("You win!");
       else if( guessNumber < numToGuess)
           System.out.println("Too less!");
       else if( guessNumber > numToGuess
           System.out.println("Too high;
       }while(guessNumber != numToGuess);
  
   }
  
}