13. Write a Java program that simulates a guessing number game. The program will generate a random value the user needs to guess and keep asking the user for a guess until the user provides the expected value. If a value has already provided, the program will print the message “Value already provided”. If the value is higher than the value to guess, the program will print“Too high”; if it is less, the program will print the message “Too low”. Once the user enters the expected value, the program will print the number of attempts.
import java.util.Random;
import java.util.Scanner;
public class GuessingNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// create instance of Random class
Random rand = new Random();
int attempts = 0;
// generate a random value the user needs to guess in range 1 to 100
int randomValue = rand.nextInt(100) + 1;
int userValue = -1;
while (userValue != randomValue) {
//keep asking the user for a guess until the user provides the expected value.
System.out.print("Enter value: ");
userValue = input.nextInt();
//If the value is higher than the value to guess, the program will print "Too high";
if (userValue > randomValue) {
System.out.println("Too high.");
}
//if it is less, the program will print the message "Too low".
if (userValue < randomValue) {
System.out.println("Too low.");
}
attempts++;
}
//If a value has already provided, the program will print the message "Value already provided"
System.out.println("\nValue already provided.");
//Once the user enters the expected value, the program will print the number of attempts.
System.out.println("The number of attempts: " + attempts + ".");
}
}
Comments
Leave a comment