Correcting Java program code snippets
I'm a beginner. I learn Java and modify my exam by answering the questions in the past exam papers. There's another question I'm trapped in
Consider the following code snippet, which reads the input command and 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 the string "forward" into CMD, but the program outputs "unknow command: forward"
a) Explain in detail why this happened
b) What changes should be made to the code to correct this error
I would appreciate it if someone could help me answer questions a) and b)
PS: I know this is not a website that only looks for answers (#noeasywayout), so I will try not to be greedy here I apologize for any inconvenience
Solution
This old chestnut
In Java, = = tests whether two operands are identical. Obviously, they are not (one object is a string constant and the other is read from the input)
Use string The equals () method compares their values
Try this:
if (cmd.equals("forward")) robot.forward(1); else if (cmd.equals("turn")) robot.turn(); else System.out.println("UnkNown command: " + cmd);
By the way, with this code pattern, please pay attention to calling on CMD Equals () if it's null - you'll get an NPE A common way to avoid this without adding any code is to use "Yoda test" (a test with "reversal" logic):
if ("forward".equals(cmd)) robot.forward(1); else if ("turn".equals(cmd)) robot.turn(); else System.out.println("UnkNown command: " + cmd);
If CMD is null, this code will not throw NPE