无法打破while循环

时间:2011-06-22 06:15:43

标签: 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);
            }
        }

    }
}

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

4 个答案:

答案 0 :(得分:7)

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

input.equals("-1");

更好的方法是

"-1".equals(input);

因为它也处理空输入

答案 1 :(得分:5)

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

答案 2 :(得分:0)

==equals进行比较时存在差异。第一个比较指针,后者的内容。这可能是你的问题。

答案 3 :(得分:-1)

您将字符串与==进行比较,这会产生问题。你可以有许多不同的String-Objects,它们都显示“-1”。 ==测试,如果你在左侧和右侧有完全相同的对象。您想知道,左侧和右侧的对象是否具有相同的内容。

更好的尝试

input.equalsIgnoreCase("-1");

编辑:回答评论:input.equalsIgnoreCase(“ - 1”)与“-1”的输入引号(“ - 1”)相同,因为“1”中没有大写/小写字母-1" 。但是,在Strings的情况下,我更喜欢equalsIgnoreCase,因为它是在String上定义的,而不是在Object上定义的。尽管如此,当为String类重写equals-definition时,它在这个例子中也起作用,并且不需要“ignoreCase”。