利用Scanner.next()方法获取用户输入,并将其当作方法参数进行判断时出错。
main方法:
import java.util.*;
public class mapTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String command = sc.nextLine();
Self me = new Self("I", 0);
me.move(command);
}
}
Self类的move方法:
public void move(String direction){
if (direction == "n"){
System.out.println("Heading to the North");
}else if (direction == "w"){
System.out.println("Heading to the West");
}else if (direction == "s"){
System.out.println("Heading to the South");
}else if (direction == "e"){
System.out.println("Heading to the East");
}else{
System.out.println("Wrong Code!");
}
}
输出
n
Wrong Code!