我需要一些帮助。我试图让用户创建基础结构,如果用户从已经存在的基础结构列表中提供正确的名称并使用其中的值。但后来我得到了这个错误:线程“main”java.lang.NullPointerException中的异常 TownObject是内部基础结构的抽象类。 什么可能导致运行时错误?提前谢谢。
townObject commtowers = new infrastructure("telekom", "communication towers", 50);
townObject busstop = new infrastructure("litatrek", "bus stop", 30);
townObject[][] ton = new townObject[20][20];
String iname;
System.out.println("Enter infrastructure name : ");
iname = sc.nextLine();
sc.nextLine();
for (int i=0; i < rows; i++){
for (int j=0; j < columns; j++){
****if (iname.equalsIgnoreCase(ton[i][j].getName())
{
ton[x][y] = new infrastructure(infName, infType, infCost);
}
else
{
System.out.println("Infrastructure is not found.");
}
}
}
答案 0 :(得分:0)
Java中Objects
的默认值为null
。这也适用于Object
数组的元素。
虽然数组ton
本身已实例化,但其各个元素仍然是null
,需要进行分配。在调用对它们的任何操作之前,您需要实例化数组的元素:
for (int i=0; i < ton.length; i++) {
for (int j=0; j < ton[i].length; j++) {
ton[i][j] = new townObject();
ton[i][j].setName(...);
}
}