-1
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?

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
hkvega
  • 305
  • 3
  • 8
  • 12

4 Answers4

7

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

user809790
  • 81
  • 3
5

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.

Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
0

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

M Platvoet
  • 1,679
  • 1
  • 10
  • 14
-1

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.

grackkle
  • 776
  • 1
  • 9
  • 26
  • You might like to add an example of when `input.equalsIgnoreCase("-1")` and `input.equals("-1")` are not the same thing. ;) – Peter Lawrey Jun 22 '11 at 08:02