我正尝试在Java中创建一个用户提示输入行宽和列长度的2D游戏。 A“世界”对象被创建,看起来像这样印刷时(其中P是玩家的角色):Java 2D游戏NullPointerException
P---
----
----
----
然后,用户可以输入上,下,左,右或退出应围绕移动P和如果移动将角色从地图上移开,则什么也不做。我的问题是在我进入的宽度和长度,我得到以下错误:
java.lang.NullPointerException
at World.displayWorld(Driver.java:90)
at Driver.main(Driver.java:28)
我认为,这意味着Java是看到worldDimensions.length为空/空?我认为当世界对象被创建时,我正在为它赋值。任何指导都非常感谢!
这里是我的代码:
import java.util.Scanner;
public class Driver {
public static void main(String args[]) {
//Create a scanner object
Scanner input = new Scanner(System. in);
boolean exit = true;
//Prompt user to enter world width and height
System.out.print("World width: ");
int userWidth = input.nextInt();
System.out.print("World height: ");
int userHeight = input.nextInt();
//Create a world object
World world1 = new World(userWidth, userHeight);
world1.displayWorld();
System.out.println("Possible inputs: up, down, left, right, exit");
while (exit = true) {
//display world
world1.displayWorld();
System.out.print("ACTION > ");
String userAction = input.next();
if (userAction == "up" || userAction == "down" || userAction == "left" || userAction == "right" || userAction == "exit") {
switch (userAction) {
case "up":
world1.moveUp();
break;
case "down":
world1.moveDown();
break;
case "left":
world1.moveLeft();
break;
case "right":
world1.moveRight();
break;
case "exit":
exit = false;
break;
}
} else {
System.out.println("Invalid Input. Possible inputs are: up, down, left, right, or exit.");
}
}
}
}
class World {
static private char[][] worldDimensions;
static private int characterRow;
static private int characterColumn;
public World(int userWidth, int userHeight) {
char[][] worldDimensions = new char[userHeight][userWidth];
int characterRow = 0;
int characterColumn = 0;
for (int row = 0; row < worldDimensions.length; row++) {
for (int column = 0; column < worldDimensions[row].length; column++) {
if (characterRow == row && characterColumn == column) {
worldDimensions[row][column] = (char)
'P';
} else {
worldDimensions[row][column] = (char)
'-';
}
}
}
}
public void displayWorld() {
for (int row = 0; row < worldDimensions.length; row++) {
for (int column = 0; column < worldDimensions[row].length; column++) {
System.out.print(worldDimensions[row][column]);
}
System.out.println();
}
}
public void moveUp() {
if (characterRow - 1 >= 0) {
characterRow--;
}
}
public void moveDown() {
if (characterRow + 1 <= worldDimensions[0].length) {
characterRow++;
}
}
public void moveLeft() {
if (characterColumn - 1 >= 0) {
characterColumn--;
}
}
public void moveRight() {
if (characterRow + 1 <= worldDimensions.length) {
characterRow++;
}
}
}
使用['equals()方法来比较strings'(http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in- JAVA)。还要检查['什么是空指针异常,以及如何解决它?'](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do -i-fix-it) – sam
为了将来的参考,它有用于指示空指针在哪一行 - 而不是我们必须找到它。 – Sh4d0wsPlyr
这里至少有三个错误 - 使用'='而不是* *'exit',使用'=='比较字符串,并将冗余转换为'char' ... – Makoto