Break DO While Loop Java?

I'm new to JAVA and I'm not sure how to break the DO WHILE loop that I use in my code below? I thought I could enter -1 to break or all the other numbers to continue the loop.

import javax.swing.*;
public class Triangel {

public static void main(String[] args) {

int control = 1;

while (control == 1){

    String value = JOptionPane.showInputDialog("Enter a number or -1 to stop");

    if(value == "-1"){
         control = 0;
    }
System.out.println(value);
}

}

}

+5
source share
3 answers

You need to use .equals()instead ==, for example:

if (value.equals("-1")){
    control = 0;
}

When you use ==, you check referential equality (i.e. this is the same pointer), but when you use .equals(), you check the equality of values ​​(i.e. whether they point to the same thing). This .equals()is usually the right choice.

You can also use breakto exit the loop, for example:

while( true ) {
    String value = JOptionPane.showInputDialog( "Enter a number or -1 to stop" );
    System.out.println( value );
    if ( "-1".equals(value) ) {
        break;
    }
}
  • == vs .equals() . ==
+9

String.equals(). value == "-1" ,

+5

You can use break:

while (true) {
    ...
    if ("-1".equals(value)) {
        break;
    }
    ...
}
+3
source

All Articles