我正在尝试允许通过网格移动并使用字符串显示我当前的位置。如果我在a1上并输入' down'我将在b1。 (我是java的新手。)
public class ClassMethodtest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner replay = new Scanner(System.in);
String answer;
do{
MoveClass newMoveClass = new MoveClass();
newMoveClass.MoveAround();
newMoveClass.Location();
System.out.println("move again?");
answer = replay.next();
} while(answer.equals("yes"));
}
public class MoveClass {
private final String array[] = {"A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4",
"C1", "C2", "C3", "C4", "D1", "D2", "D3", "D4"};
private final Scanner kb = new Scanner(System.in);
private String location;
public void MoveAround(){
System.out.println("move nigga");
String answer = kb.next();
switch (location) {
case "A1":
if(answer.equals("down")){
location = array[4];
}
else if(answer.equals("right")){
location = array[1];
} break;
//etc.....
这会引发空指针异常,我不明白为什么。
答案 0 :(得分:2)
private String location;
位置为空。你需要设置初始位置,如:
private String location = array[6];