Reputation: 83
This code will take user input from the console, and go to one of two places depending on if the input is an Integer or not. The exception is caught and then dealt with by reading it again to get it out of the stream. (not sure if Scanner counts as a stream, but I know that without the input.next() it will never leave that section).
So what I want to know is how can I exit the loop if I get to the MismatchException with a certain input. I've tested the if(bad_input == anything) and it turns out I can never actually get there. I tried some print statements in that block that never executed. Would appreciate any help.
Solved
Not sure how to close the question, but this has been solved. I was incorrectly using == to check two strings. The correct way is to use bad_input.equals("x").
public static void main(String[] args){
//read input from console
Scanner input = new Scanner(System.in);
boolean loop = true;
while(loop){
//inputting "1 2 d 1" will evaluate each term separately and output at once
try{
//choice = console input only in INTEGER
int choice = input.nextInt();
System.out.println("Input was " + choice);
} catch (InputMismatchException ex){
//here if input != INTEGER
String bad_input = input.next();
System.out.println("Bad Input: " + bad_input);
//need to figure out how to exit loop!!
if(bad_input == "x"){
loop = false;
return;
}
continue;
}
}
}
Upvotes: 1
Views: 2549
Reputation: 22
May be you should use equalsIgnoreCase method.
if (bad_input.equalsIgnoreCase("x")) {
And to exit the loop at any value other then integer, you can simply use break.
catch (InputMismatchException ex) {
// here if input != INTEGER
String bad_input = input.next();
System.out.println("Bad Input: " + bad_input);
break;
}
Upvotes: 1
Reputation: 1817
In java String comparison is using equals function "==" might not work
Change
if (bad_input == "x") {
loop = false;
return;
}
To
if (bad_input.equals("x")) {
loop = false;
return;
}
Upvotes: 2
Reputation: 81
Well I think you need to use
if(bad_input.equals("x")){
loop = false;
return;
}
== checks for same reference
.equals checks for same values
Upvotes: 1
Reputation: 2210
break;
will exit the loop immediately. What you're doing should also work though. I'm not sure you need the if
statement though, the whole catch block will be executed if and only if the input isn't an integer.
Upvotes: 1