Correcting a Java Program Code Fragment
java, java.util.scanner
Solution
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:
if (cmd.equals("forward"))
robot.forward(1);
else if (cmd.equals("turn"))
robot.turn();
else
System.out.println("Unknown command: " + cmd);
BTW, with this pattern of code, beware calling `.equals()` on `cmd` if it is `null` - 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):
if ("forward".equals(cmd))
robot.forward(1);
else if ("turn".equals(cmd))
robot.turn();
else
System.out.println("Unknown command: " + cmd);
This code won't throw an NPE if `cmd` is `null`
Problem
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.