Answer to Question #216734 in Java | JSP | JSF for Zenifer

Question #216734


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.






1
Expert's answer
2021-07-13T13:36:20-0400


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 + ".");
    }
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS