Reputation: 527
I found this code online as a password loop game, it's working fine, but my question is: how?
What does happen in this catch block exactly?
I'm curious about this line specifically:
reader.next();
boolean loop = true;
Scanner reader = new Scanner(System.in);
System.out.println("PIN: ");
while (loop) {
try {
Integer Code = reader.nextInt();
if (Code == 8273) {
System.out.println("Access granted");
loop = false;
} else {
System.out.println("Access denied");
}
} catch (Exception e) {
System.out.println("Please enter a valid PIN!");
reader.next();
}
}
Edit : of course I did deliberately input a Non-integer input to cause the exception.
Edit2 : When I removed that line, the program kept printing Please enter a valid PIN! For ever.
Upvotes: 1
Views: 42
Reputation: 121820
In fact, what the programmer really wanted here is to capture the next line of input, and verify whether that was a valid integer.
But the code is, admittedly, very confusing. And it relies on the fact that by default, when you "swallow" the next token with anything but .nextLine()
with a Scanner
, it relies on the current delimiter, which by default matches a newline.
Not good.
Here is a version which is more explicit:
String input;
int code;
while (true) {
System.out.print("PIN: ");
input = reader.nextLine();
try {
code = Integer.parseInt(input);
} catch (NumberFormatException ignored) {
// not an integer!
System.out.println("Enter a valid PIN!");
continue;
}
if (code == 8273)
break;
System.out.println("Access denied");
}
System.out.println("Access granted");
Upvotes: 1
Reputation: 305
The catch block simply catches the exception when anything other than an integer is entered. Since Code
is an Integer
, the input would have to be an integer. After catching the exception and printing the error, the reader moves to the next input until a proper value is entered, and the boolean loop
becomes false, which ends the while loop at the end of the if
statement once the correct value is entered.
Upvotes: 1
Reputation: 201517
If nextInt
throws an exception (because the value entered isn't an int
), then the catch
block is entered. The last line of which,
reader.next(); // <-- discards invalid token.
Removes the invalid token and then the loop iterates.
Also, don't box the Code
1
int code = reader.nextInt();
1Using an Object type and then testing equality with ==
is a bad idea™. Also, by convention Java variable names start with a lower case letter.
Upvotes: 1