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);
}
}
}
The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement following the loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
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.
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.
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;
}
}
==
vs .equals()
see Difference Between Equals and ==
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With