8

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);
}

}

}

3D-kreativ
  • 9,053
  • 37
  • 102
  • 159
  • 5
    This is not a `DO... WHILE` loop, this is a `WHILE` loop. You break it by issuing `break;` anywhere inside the loop. – Shef Sep 10 '11 at 07:06
  • Triangle : http://www.beedictionary.com/common-errors/angel_vs_angle – zengr Sep 10 '11 at 07:07

3 Answers3

14

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;
    }
}
Community
  • 1
  • 1
Nate W.
  • 9,141
  • 6
  • 43
  • 65
  • 3
    == compares an object for reference equality, that is, do they refer to the *exact* same object? If I have a structure that holds an integer, and I say new Structure(4) == new Structure(4), this will be false because although I've initialized the structure's integer to 4 in both objects they are different objects. However, if I overload equals (and hashcode, see the javadocs) properly, new Structure(4).equals(new Structure(4)) will print true - even though they're different objects, they are the same thing as per their equals contract. – MetroidFan2002 Sep 10 '11 at 07:25
5

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

JesusFreke
  • 19,784
  • 5
  • 65
  • 68
3

You can use break:

while (true) {
    ...
    if ("-1".equals(value)) {
        break;
    }
    ...
}
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95