Reputation: 1127
I am very new to Java and I am trying to make a lottery game and I am stuck on the first step. The first step is that the user enters their input and if it's a number and between 1 - 100 then I want the user to exit out of the while loop but If the user enters a number bigger than 100 or smaller than one or not a number, then it should go back and ask the user to input a number again. I did something similar to this with python but in java it doesn't wait for my next input!!
here is my code:
public class Lottery {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("\t \tWelcome to the Lottery!");
boolean boolCheck = true;
System.out.println("Please enter in a number between 1 and 100: ");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(isr);
String input="";
while (true) {
try {
input = buffer.readLine();
buffer.close();
input.trim();
int intInput = Integer.parseInt(input);
if (intInput >= 1 && intInput <= 100) {
break;
}
}
catch (IOException e) {
System.out.println("An input eror has occured");
}
catch (NumberFormatException e) {
System.out.println("Please enter in a number");
}
}
}
Basically if there is an error, I want it to go back to the input instead of infinite looping.
Upvotes: 1
Views: 1937
Reputation: 310957
You should not be calling close()
inside the loop, or catching IOException
inside the loop, or else issuing a break
if you catch one, other than SocketTimeoutException
. You should also be testing every readLine()
return value for null
, and breaking out of the loop if you get it.
Upvotes: 0