I am a beginner level of studying java and revising for my exams through answering the questions on previous past exam papers and there is one question that I am stuck on.
Consider the code fragment below that reads an input command then processes it.
String cmd = scanner.next();
if (cmd == "forward" )
robot.forward(1);
else if (cmd == "turn" )
robot.turn();
else
System.out.println("Unknown command: " + cmd);
When testing the program the scanner reads in the String “forward” into cmd, but the program outputs “Unknown command: forward”.
a) Explain, in detail, why this occurs.
b) What changes should be made to the code to correct this error.
If someone can help me answer question a) and b) I would be grateful.
p.s. I understand that this isn’t a website to just look for answers (#noeasywayout) so I’m going to try my best not to act greedy here. My apologies for any inconvenience.
This old chestnut…
In java,
==tests if the two operands are the exact same object, which obviously they are not (one of the objects is a String constant, the other was read from input).Use
String.equals()method to compare their value.Try this:
BTW, with this pattern of code, beware calling
.equals()oncmdif it isnull– you’ll get a NPE. A common way to avoid this without adding any code is to use a “yoda test” (one with a “reversed” logic):This code won’t throw an NPE if
cmdisnull