我需要制作一个棋盘游戏,我从阵列的左下角开始[3] [0]“Ursa Major”。当我向“西”移动时,我得到一个NullPointerException。我还需要一些帮助对角移动到[2] [1]“northeast”,但不知道如何为它编写代码。任何帮助将不胜感激。
//Declare Variables
Map map;
String input;
Scanner scan;
int row, col;
//Initialize Varibales
map = new Map();
scan = new Scanner(System.in);
row = 3; col = 0;
//Begin user dialog
System.out.println("Welcome to the Great Cal Poly Underground");
input ="";
while(!input.equals("quit"))
{
System.out.println(map.rooms[row][col].name);
System.out.print(">");
input = scan.nextLine().toLowerCase();
if (input.equals("w"))
{ if(map.rooms[row][col].isValidExit("w"))
col--;
else
System.out.println("You cant go that way");
}
else
if (input.equals("e"))
{ if(map.rooms[row][col].isValidExit("e"))
col++;
else
System.out.println("You cant go that way");
}
这是我的用户界面,这是我的地图
Room[][] rooms = new Room[4][4];
Map()
{
Room lectureHall = new Room();
Room cafeteria = new Room();
lectureHall.name = "Ursa Major";
lectureHall.exits = new String []{"e"};//can add north south west
cafeteria.name = "Los Olivos";
cafeteria.exits = new String []{"w"}; // can add north south east
rooms[3][0] = lectureHall;
rooms[2][1] = cafeteria;
这是我的房间
boolean isValidExit(String anExit)
{
boolean result = false;
int index = 0;
while (result == false && index < exits.length)
{
if(exits[index].equals(anExit))
result = true;
index++;
}
return result;
答案 0 :(得分:2)
rooms
有16个引用,但只设置了两个(rooms[3][0] = lectureHall; rooms[2][1] = cafeteria;
)。您需要为其余索引创建对象。
答案 1 :(得分:1)
用Java初始化数组:
Room[][] rooms = new Room[4][4];
仅初始化rooms
数组,这意味着只有数组不能为空。
但是,任何“内部”对象都没有初始化。
如果您希望热切地创建房间然后设置其属性,请执行以下操作:
Room[][] rooms = new Room[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
rooms[i][j] = new Room(...);
}
}
答案 2 :(得分:0)
考虑上面的所有答案,也,你的起始单元格是房间[3] [0],如果你想要“西”,你就是递减col变量:
if (input.equals("w"))
{ if(map.rooms[row][col].isValidExit("w"))
//you are decrementing col, which will become -1 after decrementing
col--;
else
System.out.println("You cant go that way");
}
然后程序在循环中返回到开头,在那里显示当前房间的名称:
while(!input.equals("quit"))
{
System.out.println(map.rooms[row][col].name);
System.out.print(">");
并且由于col = -1,你正在尝试map.rooms [3] [ - 1] ,这肯定会导致异常。
确保您没有引用&lt; 0