问题描述
我有一个 2D 对象数组,我试图从文本文件中存储数据字段“type”,但出现空指针错误。
Cell[][] worldArray = new Cell[40][40];
for (int i = 0; i < worldArray.length; i++) {
String line = lines.get(i);
String[] cells = new String[40];
cells = line.split(";");
if (cells.length != 40) {
throw new IllegalArgumentException("There are " + i
+ " cells instead of the 40 needed.");
}
for (int j = 0; j < worldArray[0].length; j++) {
worldArray[i][j].type = Integer.parseInt(cells[j]);
}
这是我的 Cell 类
import java.awt.*;
public class Cell {
public static int cellSize;
public int x;
public int y;
public int type;
Cell(int x,int y,int type) {
this.x = x;
this.y = y;
this.type = type;
解决方法
您已正确初始化对象数组:
Cell[][] worldArray = new Cell[40][40];
但此时数组是空的,没有值。换句话说,在像 i,j 这样的给定点索引处,那里没有 Cell 对象。您需要在这些位置输入一个新的 Cell 对象。所以在你的代码中:
for (int j = 0; j < worldArray[0].length; j++) {
worldArray[i][j].type = Integer.parseInt(cells[j]);
}
当你执行 worldArray[i][j].type
时你会得到一个 NPE,因为 worldArray[i][j]
是空的,直到你为它设置一个值。有关处理对象数组的示例,请参见此处:https://www.geeksforgeeks.org/how-to-create-array-of-objects-in-java/