3D-kreativ
3D-kreativ

Reputation: 9301

Break DO While Loop Java?

I'm new into JAVA and I'm not sure how to break a the DO WHILE loop that I use in my code below? I thought I could enter -1 to break or all 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);
}

}

}

Upvotes: 8

Views: 44278

Answers (3)

Nate W.
Nate W.

Reputation: 9249

You need to use .equals() instead of ==, like so:

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

When you use == you're checking for reference equality (i.e. is this the same pointer), but when you use .equals() you're checking for value equality (i.e. do they point to the same thing). Typically .equals() is the correct choice.

You can also use break to exit a loop, like so:

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

Upvotes: 14

Petar Ivanov
Petar Ivanov

Reputation: 93010

You can use break:

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

Upvotes: 3

JesusFreke
JesusFreke

Reputation: 20262

You need to use the String.equals() method when comparing strings. Your value == "-1" code is checking reference equality, not value equality

Upvotes: 5

Related Questions