0

I have tried all the ways i can think of to break this loop, but none have worked. I was wondering if anyone can help.

import java.io.*;
import java.util.*;
public class Tester
{
    public static void main(String args[])
    {
      int j;
        for(j=5;j>4;j++)
        {
            Scanner kbReader = new Scanner(System.in);
            System.out.print("Type in a sentence and press ENTER. ");
            String a = kbReader.next( );
            String b = a.toUpperCase();
            System.out.println(b);
            if( b == "EXIT" )
                break;
        }
}
}
  • 5
    Don't compare `String` values using `==`. Use `equals()`. Also no need to create a `new Scanner` at each iteration. Declare it once, outside the for loop. – Alexis C. Jan 02 '14 at 16:01
  • 2
    Voting to re-open. The questions are **not duplicates**, even if the underlying solution is the same. – Duncan Jones Jan 02 '14 at 16:07
  • Why you put for(j=5;j>4;j++)? If you want infinite loop you can use while(true) or for(;;). For comparing String you should use equals (as already suggested) – Anirban Pal Jan 02 '14 at 16:08
  • 2
    @unohu You mean `while(true)`. Always use that in preference to `for(;;)`, which is just confusing. – Duncan Jones Jan 02 '14 at 16:09
  • @Duncan What do you mean by "not duplicates"? It is true that question subject is about breaking loop, but problem is in way OP compares strings. Also question is not about how to create infinite loop. Improving this part is optionally and can be done via comment. – Pshemo Jan 02 '14 at 16:17
  • @Duncan BTW I am not saying you are wrong, just don't understand way this is not duplicate. – Pshemo Jan 02 '14 at 16:18
  • @Pshemo Based on my research on meta, I believe questions should only be closed when the question itself is a duplicate. For instance, the questions "What colour is most popular for Ferraris" and "What colour is the live wire" shouldn't be closed as duplicates of each other, even if the answer to both is "red". – Duncan Jones Jan 02 '14 at 16:21

1 Answers1

4

Instead of

String b = a.toUpperCase();
System.out.println(b);
if( b == "EXIT" )
    break;

You should just do:

if( a.equalsIgnoreCase("EXIT") )
    break;
qwertynl
  • 3,912
  • 1
  • 21
  • 43
Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45