0

I want to break the loop by a string input . But the program is taking input infinitely.

public static void main(String[] args) {
int i;
String test;
Scanner inputString = new Scanner(System.in);  
  while(1==1){
    test=inputString.next();
    if(test=="Break"){
        break;}

  }
System.out.println("the loop actually broke");

}
abu obaida
  • 75
  • 1
  • 10

2 Answers2

1

Try to use equals method instead of == like this:

 if("Break".equals(test)){
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
  • I'd probably flip that around to `test.equals("Break")` for clarity. Also note that this code will not work as expected if input is "break" (or "BREAK", "breaK", etc). So if you want to stop execution on any capitalization variant of the string "break", you'd want to use something like `test.toLowerCase().equals("Break")` – The Head Rush Apr 15 '16 at 14:16
  • It would be: `test.toLowerCase().equals("break")` (no capital 'B') – xgord Apr 15 '16 at 14:19
  • 3
    @TheHeadRush `test.toLowerCase().equals("Break")` will never be `true` ;-) – SubOptimal Apr 15 '16 at 14:20
  • "Break" it is a String it depend on user input, he selet to use this word he can select other word it's ok – Abdelhak Apr 15 '16 at 14:22
  • Doh! That's what i get for hurriedly pasting. You'd want to use `test.toLowerCase().equals("break")`. – The Head Rush Apr 15 '16 at 14:24
  • 1
    If the String's case is not important over here, you can use `if(test.equalsIgnoreCase("break")` – Shreyas Apr 15 '16 at 14:33
  • True enough. I prefer `toLowerCase` since i spend a great deal of time writing both Java and Javascript. Since each language has `String.toLowerCase` but not `String.equalsIgnoreCase` using the common method is easier on my simple mind. YMMV. – The Head Rush Apr 15 '16 at 14:51
1

You should use " test.equals("Break") " instead of " test=="Break" " because in Java " == " checks for reference equality(whether they are the same objects) but " equals() " checks for value equality(whether they are equal "logically")

Aditya kumar
  • 76
  • 1
  • 11