This may be an obvious answer but it is due tomorrow and I am completely stumped. Everything is working fine except for the if statements at the end. It seems the continueGame loop is looping the if statement infinitely. If anyone can help me with this problem, please.
import java.util.Random;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HighLOw {
public static void main(String[] args) throws IOException {
String input = null;
int number = 0;
int tries = 0;
boolean highorlow = false;
boolean continueGame = false;
boolean validInput = false;
Random random = new Random();
int randomNumber = (random.nextInt(101));
System.out.println("Welcome to the High/Low game.");
System.out.println("Guess a number between 0 and 100.");
System.out.println(
"In order to print a random number, type your number in the console and press enter.");
System.out.println("Keep going until you get the right number.");
System.out.println("Have fun.");
System.out.println(randomNumber);
while (continueGame == false) {
while (validInput == false) {
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in)); // BufferedReader variable where the user will input their answer
input = bufferedReader.readLine();
number = Integer.parseInt(input);
validInput = true;
} catch (NumberFormatException ex) {
System.out.println("Invalid input, please enter a number.");
validInput = false;
}
if (number < 0 || number > 100) {
System.out.println(
"Error, you must enter a number that is between 0 and 100");
validInput = false;
}
}
if (number < randomNumber) {
System.out.println(
number + " is too low. Please try a higher number");
tries++;
highorlow = false;
} else if (number > randomNumber) {
System.out.println(
number + " is too high. Please try a lower number");
tries++;
highorlow = false;
} else if (number == randomNumber) {
System.out.println(
"Congratulations, you guessed the right number. Now go outside.");
tries++;
System.out.println("It took you " + tries + (" tries."));
System.out.println("Game Ended");
continueGame = true;
}
}
}
}
A few hints: When you enter a valid number for the first time,
validInputwill becometrue. Then, the code proceeds to comparenumbertorandomNumberand then jumps up again to the start of thecontinueGameloop. What is the value ofvalidInputnow, and what effect will this have on thevalidInputloop? Willnumberever get a new value?Also you don’t need to do
while (validInput == false).. Justwhile (!validInput)is equivalent..