【发布时间】:2011-12-30 01:13:41
【问题描述】:
每次尝试执行以下代码时都会抛出异常。
下面是驱动,下面我给你Room和playerEnters方法的构造函数。
import java.util.Random;
import java.util.Scanner;
public class ZorkPlayer
{
public static void main (String [ ] args)
{
// create a start screen followed by introduction
int choice = 0;
while(choice != 3)
{
choice = menu();
switch (choice)
{
case 1:
//begin new game
newGame();
break;
case 2:
//change difficulty level
break;
case 3:
//exit the program
break;
default:
//invalid choice
break;
}
}
}
/**
* Creates a menu and gets a choice from the user <br>
*/
public static int menu ()
{
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to Zork!");
System.out.println("What would you like to do?");
System.out.println("\t1- Start a new game");
System.out.println("\t2- Choose difficulty level (not yet available)");
System.out.println("\t3- Exit the program");
int choice = kb.nextInt();
return choice;
}
public static void newGame()
{
final int DEFAULT_ROOMS = 5;
Random rng = new Random ();
int numRooms = rng.nextInt(5) + DEFAULT_ROOMS;
int playerPos = 0;
Room dungeon[] = new Room[numRooms];
dungeon[playerPos].playerEnters();
for (int i = 0; i < dungeon.length; i++)
{
System.out.print (dungeon[i].getMap ( ));
}
}
}
房间的构造函数
private int monster = 0; //initializes with no monster spawned
private int player = 0; //initializes with no player present
private int weapon = 0; //initializes with no weapon present
public Room()
{
//creates a new room and determines whether the new room has a monster or not
Random rng = new Random();
int monsterSpawn = rng.nextInt (2); //determines whether or not a monster will spawn in the room
if (monsterSpawn == 0)
{
new Monster(); //if a monster is spawned, creates a new monster and sets the value of monster to present
setMonster(1);
}
else
setMonster(0); //otherwise leaves the value of monster to default
setPlayer(0); //sets the presence of player to false
setWeapon(0); //sets the presence of weapon to false
}
playerEnters 方法
public void playerEnters()
{
setPlayer(1);
}
每当在驱动程序中调用playerEnters 方法时抛出NullPointerException,然后在调用getMap 方法时再次抛出。
【问题讨论】:
-
您的代码格式似乎有点损坏。另外,你有
setPlayer的代码吗? -
NPE 通常非常容易调试。您是否在调试器中单步调试过您的代码?
-
嗨,Caleb,下次您可能想从您的 sscce 中删除个人信息。 :D
-
是的,我知道个人信息,我只是在截止日期前没有选择。 =/ 是的,我将为 setPlayer 添加代码,不,我还没有通过调试器运行它。
标签: java arrays nullpointerexception