无法打破while循环

hkv*_*ega -1 java loops

public void play () {
    int anInteger;
    //guess return code
    int code;

    while (true) {
        String input=null;
        input = JOptionPane.showInputDialog("Please enter an integer");

        if (input == "-1") {
            //JOptionPane.showMessageDialog(null, input);
            System.exit(0);
            break;
        } else {
            if (input==null) {
                 System.exit(0);
            } else if (input.isEmpty()) {
                 continue;
            } else {
                anInteger = Integer.parseInt(input);
                code = this.oneGuess (anInteger);
                //JOptionPane.showMessageDialog(null, anInteger);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我想,如果用户输入-1,显示程序将不再提示消息框.上面是我提出的代码,到目前为止.为什么它不起作用?

小智 7

字符串比较不适用于"=="运算符,使用"String.equals(Object)"函数

input.equals("-1");
Run Code Online (Sandbox Code Playgroud)

更好的方式

"-1".equals(input);
Run Code Online (Sandbox Code Playgroud)

因为它也负责空输入


Esk*_*ola 5

您正在将字符串(对象)与==运算符进行比较,该运算符检查两个对象引用是否引用同一对象实例.相反,您应该使用该equals方法来比较它们.