我有一个名为Player的类,它定义了Player的特性。我在另一个类中有一个名为readPlayer的方法:
void readPlayer(String playerInfo) {
int j = 0;
int playerNumber = 0;
int playerCount = 0;
String splitPipe = "\\|"; // split by pipe
String splitColon = "\\:"; // split by colon
String splitInput[] = playerInfo.split(splitPipe + "|" + splitColon);
for (int i = 0; i < splitInput.length; i += 5) {
playerCount++; // keeps track of how many players there are
}
players = new Player[playerCount];// initializes array to amount of players
while (playerNumber < playerCount) {
players[playerNumber] = new Player(Integer.parseInt(splitInput[j]), splitInput[j + 1], splitInput[j + 2],
splitInput[j + 3], splitInput[j + 4]);
j += 5;
playerNumber++;
}
pR.printPlayers(players); //ERROR: NullPointerException thrown here
}
但是当我尝试将player数组传递给另一个类的printPlayers时,它会给我和NullPointerException错误
错误详情:
Exception in thread "main" java.lang.NullPointerException
at ca.bcit.comp2613.PlayerReader.readPlayer(PlayerReader.java:30)
at ca.bcit.comp2613.Lab2.main(Lab2.java:16)
这是我的主要方法:
static PlayerReader p = new PlayerReader();
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("Usage java -jar project.jar <input String>");
System.exit(-1);
} else {
p.readPlayer(args[0]);
}
}
}
这是我的printPlayer方法 - 没有什么特别的,现在不做任何事情
public class PlayerReport {
public void printPlayers(Player players[]) {
}
}
答案 0 :(得分:0)
public class Player {
public Player(int parseInt, String string, String string2, String string3,
String string4) {
// Do initialization
}
public static void main(String args[]) {
// if(args.length == 0) {
// System.out.println("Usage java -jar project.jar <input String>");
// System.exit(-1);
// } else {
// p.readPlayer(args[0]);
// }
PlayerReader p = new PlayerReader();
p.readPlayer("playerInfo");
}
}
class PlayerReport {
public void printPlayers(Player players[]) {
System.out.println("Printing....");
}
}
class PlayerReader {
void readPlayer(String playerInfo) {
int j = 0;
int playerNumber = 0;
int playerCount = 0;
String splitPipe = "\\|"; // split by pipe
String splitColon = "\\:"; // split by colon
String splitInput[] = playerInfo.split(splitPipe + "|" + splitColon);
for (int i = 0; i < splitInput.length; i += 5) {
playerCount++; // keeps track of how many players there are
}
Player[] players = new Player[playerCount];// initializes array to
// amount of players
while (playerNumber < playerCount) {
// players[playerNumber] = new
// Player(Integer.parseInt(splitInput[j]),
// splitInput[j + 1], splitInput[j + 2], splitInput[j + 3],
// splitInput[j + 4]);
players[playerNumber] = new Player(1, "3", "4", "5", "6");
j += 5;
playerNumber++;
}
PlayerReport pR = new PlayerReport();
pR.printPlayers(players); // ERROR: NullPointerException thrown here
}
}
答案 1 :(得分:0)
在另一个答案中提到,你没有展示你如何实例化“pR”或“玩家”对象。
不确定“pR”对象是什么,但这是导致Null指针的原因。