Write a program in Java where a user of this program will play a game in which he/she needs to guess a target number, which is a number that the program has randomly picked in the range that the user chooses. The program will repeatedly prompt for the guessed number and provide a clue whether the guessed number is bigger or smaller than the target number, until the guessed number equals the target number.
//code:
import java.util.Scanner;
public class Main{
// Function that implements the
// number guessing game
public static void numberGuessingGame()
{
// Scanner Class
Scanner sc = new Scanner(System.in);
//range of randomly choosen numbers(lowrange and highrange)
int lrange,hrange;
System.out.println(" Enter 2 numbers that the target number should be in the range : ");
lrange=sc.nextInt();
hrange=sc.nextInt();
// Generate the numbers
int target_number = lrange + (int)(hrange* Math.random());
int i, guess;
// Interate over until target guess
for (i = 0; ; i++) {
System.out.println(
"Guess the number:");
// Take input for guessing
guess = sc.nextInt();
// If the number is guessed
if (target_number == guess) {
System.out.println(
"Congratulations! You guessed the number.");
break;
}
else if (target_number > guess) {
System.out.println(
"The number is greater than " + guess);
}
else if (target_number < guess) {
System.out.println(
"The number is less than " + guess);
}
}
}
// Driver Code
public static void main(String arg[])
{
// Function Call
numberGuessingGame();
}
}
//screenshot
---------------------------------------------------------------------
Get Answers For Free
Most questions answered within 1 hours.