The following question is from a quiz I took a few weeks ago and got incorrect, but the answer wasn't provided:
Consider the following code, which contains no compile errors:
String secret = "Ellie"; Scanner kb = new Scanner(System.in); System.out.println("Guess which name I'm thinking of:"); String guess = kb.next(); if (guess == secret) { System.out.println("Wow! You're smart!"); } else { System.out.println("Wrong!"); System.out.println("You guessed: " + guess); System.out.println("The correct answer was: " + secret); }
Suppose the user enters "Ellie" at the prompt. What output would result, and why that output and not the other output?
Here was my incorrect answer:
The output would be the else statement "WRONG!" because of the capitalization of the letter 'E'. A solution to this would be to either change the String secret to "ellie" as well as the user's guess, or one can write in the ignoreCase keyword to String secret.
The program actually outputs "Wrong", I tested it.
Aside from 开发者_Go百科simply knowing the answer, could someone really explain this to me so I can understand the concept better?
The == does a reference comparison, and so it'll always say 'Wrong!', even if the two string references are equal. In order for it to match correctly, it would have to use secret.equals( guess )
.
In java:
- the
==
operator tests if the two objects are the same exact instance - the .equals() method of String compares if the objects "have the same value"
Since the user input the value, it's a new instance of String, so it will never be true that secret == input
.
You should always use str1.equals(str2)
when comparing Strings.
精彩评论