The user inputs the number and the computer guesses it by us
The user inputs the number and the computer guesses it by using the upper bound and the lower bound.
Write a Java program to implement the number guessing game. Have the user enter the upper bound (less than 1 million) (assume the lower bound is 1). The user then enters the number to find. Your program should display the number being guessed and the number of the current guess.
Solution
GuessGameTest.java
import java.util.Random;
import java.util.Scanner;
public class GuessGameTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random r = new Random();
System.out.print(\"Enter the upper bound: \");
int upper = scan.nextInt();
int secretNumber = r.nextInt(upper) +1;
System.out.println(\"Guessing game begins!\");
int n = 0;
int count = 0;
while(n!=secretNumber){
System.out.print(\"Enter your guess number: \");
n = scan.nextInt();
if(n < secretNumber){
System.out.println(\"Guess Lower!\");
}
else if(n > secretNumber){
System.out.println(\"Guess Higher!\");
}
count++;
}
System.out.println(\"You got it right! You win!\");
System.out.println(\"The number of the current guess: \"+count);
}
}
Output:
Enter the upper bound: 100
Guessing game begins!
Enter your guess number: 50
Guess Lower!
Enter your guess number: 60
Guess Lower!
Enter your guess number: 70
Guess Higher!
Enter your guess number: 65
Guess Higher!
Enter your guess number: 63
Guess Higher!
Enter your guess number: 61
You got it right! You win!
The number of the current guess: 6
