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

}

}

2
  • 5
    This is not a DO... WHILE loop, this is a WHILE loop. You break it by issuing break; anywhere inside the loop. Commented Sep 10, 2011 at 7:06
  • Triangle : beedictionary.com/common-errors/angel_vs_angle Commented Sep 10, 2011 at 7:07

3 Answers 3

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

== 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.
5

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

Comments

3

You can use break:

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

2 Comments

Do not compare strings using == but .equals instead.
oh sorry - didn't notice this was java, thought C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.