I'm new to this and trying to teach myself (I'm only 13). So I wrote this code and have everything working except, I want it too display "number out of range, try again" message only when you enter a number higher than 100. Right now it displays "Too high, try again" and "number out of range, try again". How do i change it to display "number out of range, try again" only? Also how do i get to display "Guess a number between 1 and 100" only once and not every time you try and guess the number. Any help will be greatly appreciated.
import java.util.Scanner;
public class randomNumber {
public static void main(String[] args) {
int randomNumber;
int guessCount;
int tooHigh;
randomNumber = (int)(100 * Math.random()) + 1;
guessCount = 0;
tooHigh = 101;
Scanner keyboard = new Scanner(System.in);
int guess;
do {
System.out.println("Guess a number between 1 and 100");
System.out.println("Enter your guess");
guess = keyboard.nextInt();
guessCount++;
if (guess == randomNumber) {
System.out
.println("Congratulations your guess was correct!" +
" It took " + guessCount + " guesses.");
}
else if (guess < randomNumber) {
System.out
.println("Too low, try again .");
}
else if (guess > randomNumber) {
System.out
.println("Too high, guess again.");
}
if (guess >= tooHigh) {
System.out
.println("Number out of range, try again.");
}
} while (guess != randomNumber);
}
}
I ran it through NetBeans IDE to show you my problems.
run:
Guess a number between 1 and 100
Enter your guess
100
Too high, guess again.
Guess a number between 1 and 100
Enter your guess
101
Too high, guess again.
Number out of range, try again.
Guess a number between 1 and 100
Enter your guess
50
Too high, guess again.
Guess a number between 1 and 100
Enter your guess
30
Too low, try again .
Guess a number between 1 and 100
Enter your guess
40
Too high, guess again.
Guess a number between 1 and 100
Enter your guess
33
Too low, try again .
Guess a number between 1 and 100
Enter your guess
35
Too high, guess again.
Guess a number between 1 and 100
Enter your guess
34
Congratulations your guess was correct! It took 8 guesses
BUILD SUCCESSFUL (total time: 50 seconds)