Peyton C.
Peyton C.

Reputation: 83

How to manually exit a while loop (java)

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

Answers (5)

shivam355
shivam355

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

Geo Paul
Geo Paul

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

Ashish Gupta
Ashish Gupta

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

http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

Upvotes: 1

3ocene
3ocene

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

hehe
hehe

Reputation: 1304

Try to use break.

if(condition)
    break;

Upvotes: 2

Related Questions