1

I haven't used Java in a while and am having a simple yet frustrating error. My code is something like this:

public static void main(String[] args) throws IOException{
    String input = "";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while(input != "Q"){
        input = in.readLine().toUpperCase();
        switch(input){
            default: break;
            case "A": //do stuff break;
            case "B": //do stuff break;
        }
    }
    System.out.println("Out of the loop!"); //never reaches this statement
}

I ran the eclipse debugger and it clearly shows the input variable being changed to "Q" when entered by the user, but the while loop keeps restarting.

ashiquzzaman33
  • 5,611
  • 5
  • 30
  • 42
P. Jindra
  • 47
  • 1
  • 7
  • Do you want to `break` out of the switch statement or do you want to jump to the end of the `while` loop? Because in the latter case, the `break` targets the `switch` and needs an explicit label to work correctly. – Clashsoft Sep 27 '15 at 19:58

3 Answers3

3

Change while to

while(!input.equals("Q"))

compare string with equals() not with ==

In addition use a break; after each case otherwise you would have a fallthrough.

singhakash
  • 7,773
  • 5
  • 28
  • 61
  • 1
    .equals()! of course. thank you so much, ive been doing a lot of python recently and it's messing me up lol – P. Jindra Sep 27 '15 at 19:57
  • 1
    If you know that question is duplicate you should vote it as such instead of answering it. We don't really need thousand-th answer about that subject. I know that new users may not know it but you already have 5k, so use your *closing/flagging* privilege. – Pshemo Sep 27 '15 at 20:04
  • 1
    @Pshemo I keep that in mind next time – singhakash Sep 27 '15 at 20:10
0

You should compare the strings using equals (values comparison) instead of == (which compares references):

while (!"Q".equals(input))

Hint: if you call equals on the string literal, it will not fail with NullPointerException in case input is, by some chance, null - in such case it would just return false

Sva.Mu
  • 1,155
  • 1
  • 15
  • 24
0

You have to use input.equals("Q") when comparing strings.

mmking
  • 1,386
  • 4
  • 22
  • 35
Joel Min
  • 3,292
  • 2
  • 16
  • 38