开发者

Can't break the while loop [duplicate]

开发者 https://www.devze.com 2023-03-15 00:54 出处:网络
This question already has answers here: How do I compare strings in Java? 开发者_高级运维 (23 answers)
This question already has answers here: How do I compare strings in Java? 开发者_高级运维 (23 answers) Closed 5 years ago.
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);
            }
        }

    }
}

I want, if the user enter -1, show the program will not prompt the message box any more. Above is the code I have come up with, so far. Why it doesn't work?


String comparisons does NOT work with "==" operator, use "String.equals(Object)" function

input.equals("-1");

Better way would be

"-1".equals(input);

as it also takes care of null input


You are comparing strings, which are objects, with the == operator, which checks whether two object references refer to the same object instance. Instead you should use the equals method for comparing them.


There is a difference between comparing with == and equals. The first compares pointers, the latter contents. That is probably your issue.


You compare Strings with ==, which creates a problem. You can have many different String-Objects which all show "-1". The == tests, if you have exactly the same object on the left and right side. You want to know, if the objects on the left and right sie have an equal content.

Better try

input.equalsIgnoreCase("-1");

EDIT: To answer the comment: input.equalsIgnoreCase("-1") is the same as input.equals("-1") in the case of "-1" as there are no uppercase/lowercase letters in "-1". However, I prefer equalsIgnoreCase in the case of Strings, because it is defined on String, rather than on Object. Still, as the equals-definition is overridden for the String class, it works too in this example and "ignoreCase" is not needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消