本文介绍了循环Java时打破DO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JAVA的新手,我不知道如何打破我在下面的代码中使用的DO WHILE循环?我以为我可以输入-1来打破或所有其他数字继续循环。

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

}

}

推荐答案

您需要使用 .equals()而不是 == ,如下所示:

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

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

当你使用 == 你正在检查引用相等性(即这是相同的指针),但是当你使用 .equals()时,你正在检查值的相等性(即它们是否相同)指向同一件事)。通常 .equals()是正确的选择。

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.

您还可以使用 break 退出循环,如下所示:

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