Answer to Question #252657 in Java | JSP | JSF for kitty ku

Question #252657

Write a guessing game in java

where the computer generates a secret integer, and the user has to guess the secret integer. After every guess the program tells the user whether their number was too large or too small. Pring “Bingo” and the secret integer if the guess matches. At the end the number of tries needed should be printed.

Hints: How to generate secret number:

1. Import the class java.util.Random

2. Make the instance of the class Random, i.e., Random rand = new Random()

3. Use nextInt(upperbound) generates random numbers in the range 0 to upperbound-1


1
Expert's answer
2021-10-17T14:00:45-0400
import java.util.Random;
import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        Random random = new Random();
        int N1 = 1;
        System.out.print("Enter the upperbound: ");
        int N2 =input.nextInt();
        int randomNumber = random.nextInt(N2 - N1 + 1) + N1;
        int secret = 0;
 
        System.out.printf("The number is between %d and %d.\n", N1, N2);
 
        do
        {
            System.out.print("Guess what the number is: ");
            secret = input.nextInt();
            if (secret > randomNumber)
                System.out.println("Your guess is too high!");
            else if (secret < randomNumber)
                System.out.println("Your guess is too low!");
            else
                System.out.println("Bingo!\nThe secret Number is: "+secret);
        } while (secret != randomNumber);
    }
}

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