Fix Java code snippet

I am starting to learn java and reviewing exams to answer questions from previous exam documents, and there is one question I'm stuck with.

Consider the code snippet 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 the line "forward" in cmd, but the program displays "Unknown command: forward".

a) Explain why this is happening.

b) What changes need to be made to the code to correct this error.

If someone can help me answer the question a) and b) I would be grateful.

p.s. , -, (#noeasywayout), . .

+3
3

...

java, == , , , , ( String, ).

String.equals(), .

:

if (cmd.equals("forward"))
    robot.forward(1);
else if (cmd.equals("turn")) 
    robot.turn();
else
    System.out.println("Unknown command: " + cmd);

, , .equals() cmd, null - NPE. - " " ( "" ):

if ("forward".equals(cmd))
    robot.forward(1);
else if ("turn".equals(cmd)) 
    robot.turn();
else
    System.out.println("Unknown command: " + cmd);

NPE, cmd null

+8

cmd.equalsIgnorecase cmd.equals ==.

String cmd = scanner.next();

if (cmd.equals("forward") )
   robot.forward(1);
else if (cmd.equals("turn") ) 
   robot.turn();
else
 System.out.println("Unknown command: " + cmd);

, String , ==, .

+2

Java:

15.21.3 == !=

While == can be used to compare references of type String, such an equality test determines whether two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of the two lines s and t can be checked for equality by calling the s.equals (t) method.

+2
source

All Articles