我一直在努力为朋友制作一款游戏,但是我在课堂player[i].setName(getName(pn));
中排队Players
时遇到了问题。我希望能够在列表中设置播放器的名称或更改它们。但我一直在这条线上遇到错误。这是在我从public
更改了Player
课程中的static
变量后发生的。
"线程中的异常" main"显示java.lang.NullPointerException at worldhomicide.drinkinggame.PlayerInfo.Players.setPlayers(Players.java:16) 在worldhomicide.drinkinggame.main.Game.main(Game.java:25)"
任何帮助将不胜感激!我在下面发布了所有需要的代码。
游戏类
public class Game{
public static void main(String[] args) {
MessageHandler.gameRules(); // Display Game Information
Players.getAmount();Players.setPlayers(); // Get player data
System.out.println("What player would you like to look up?");
int choice = Integer.parseInt(EventHandler.keyboard.next()); choice -= 1;
System.out.println(Players.player[choice].name);
}
}
玩家等级
public class Players extends EventHandler {
public static int playerAmount;
public static Player[] player;
public static void setPlayers(){
player = new Player[playerAmount];
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i].setName(getName(pn));
}
}
public static void getAmount(){
MessageHandler.playerAmount();
playerAmount = Integer.parseInt(keyboard.next());
}
}
类EventHandler
public class EventHandler {
public static Scanner keyboard = new Scanner(System.in);
public static String getName(int playerNumber){
System.out.println("What is player " + playerNumber + "'s name?");
String name = keyboard.next();
return name;
}
}
玩家等级
public class Player {
public String name;
public int score;
public void setName(String name){
this.name = name;
}
}
答案 0 :(得分:7)
请注意,在setPlayers()
方法中,在循环内部,您在访问player[i].setName()
方法之前未创建Player对象。
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i] = new Player(); //you need to create Player object
player[i].setName(getName(pn));
}