Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break DO While Loop Java?

Tags:

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

}

}

like image 911
3D-kreativ Avatar asked Sep 10 '11 07:09

3D-kreativ


People also ask

What does break do in while loop Java?

The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement following the loop.

Can you break a Do-While loop?

We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.

Can you break out of a while loop Java?

To exit the while-loop, you can do the following methods: Exit after completing the loop normally. Exit by using the break statement. Exit by using the return statement.

How do you break a while loop break?

To break out of a while loop, you can use the endloop, continue, resume, or return statement. endwhile; If the name is empty, the other statements are not executed in that pass through the loop, and the entire loop is closed.


1 Answers

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;
    }
}
  • For more on == vs .equals() see Difference Between Equals and ==
like image 95
Nate W. Avatar answered Sep 29 '22 13:09

Nate W.