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
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);
}
}
Comments
Leave a comment