Write the class RandomGuess.Java where a user inputs a jumber between 1 and 1,00
ID: 3860181 • Letter: W
Question
Write the class RandomGuess.Java where a user inputs a jumber between 1 and 1,000, then determine and display if the initial guess was correct, too high, or too low, and add a loop that continuously prompts the user for the number, indicating whether the guess is high or low, until the user enters the correct value. Once the player has figured out the correct number, ask if they would like to play again using the Scanner class. If yes, restart the game with a new random number. If not, use the System.out.println(); method to display a message that thanks the user for playing the game.
Explanation / Answer
package org.students;
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
//Declaring variables
int secret, guess;
//Creating the Random class object
Random generator = new Random();
// Scanner object is used to get the inputs entered by the user
Scanner sc = new Scanner(System.in);
//This loop will continue to execute until the user enters either 'Y' or 'y'
while (true) {
//generating the random number
secret = generator.nextInt((1000 - 1) + 1) + 1;
//this loop continues to execute until the user correctly guesses the number;
while (true) {
//Getting the user guess entered by the user
System.out.print("Guess the number (Between 1-1000):");
guess = sc.nextInt();
if (guess == secret) {
System.out.println("** Correct **");
break;
} else {
if (guess > secret) {
System.out.println("** Higher **");
continue;
} else {
System.out.println("** Lower **");
continue;
}
}
}
// Getting the character from the user 'Y' or 'y' or 'N' or 'n'
System.out.print("Do you want to Play Again(Y/N) ::");
char ch = sc.next(".").charAt(0);
if (ch == 'Y' || ch == 'y')
continue;
else {
System.out.println(":: Thanks for playing the game. ::");
break;
}
}
}
}
______________________
Output:
Guess the number (Between 1-1000):500
** Lower **
Guess the number (Between 1-1000):600
** Higher **
Guess the number (Between 1-1000):550
** Lower **
Guess the number (Between 1-1000):580
** Correct **
Do you want to Play Again(Y/N) ::N
:: Thanks for playing the game. ::
_____________Could you rate me well.Plz .Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.