您好,我正在尝试在java中创建一个记录数组,您必须输入3个详细信息,一个城镇的名称,人口和所在的县。在此之前输出您要求的县的所有数据。我想知道是否有人可以告诉我为什么当我进入另一个城镇时没有发生城镇人口时会发生null.point.exception。
import java.util.*;
public class CathedralTowns
{
public static String name;
String population;
String county;
public static int count = 0;
public static int continuation = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
while (loop1 <= 0) {
System.out.println("Please enter the name of the town. ('no' to end)");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides. ('no' to end)");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town. ('no' to end)");
String populationEntered = input.nextLine();
if (nameEntered.equals("no") || populationEntered.equals("no") || countyEntered.equals("no") ) {
loop1 = 5;
System.out.println("Thank you for entering your county.");
continuation = 1;
}
WorkingDemCathedrals(nameEntered, populationEntered, countyEntered);
}
}
public static void WorkingDemCathedrals(String nameEntered, String populationEntered, String countyEntered) {
Scanner input = new Scanner(System.in);
CathedralTowns[] allTowns = new CathedralTowns[50];
allTowns[count] = new CathedralTowns();
int loop2 = 0;
int loop3 = 0;
while (loop2 == 0){
allTowns[count].name = nameEntered;
allTowns[count].population = populationEntered; //the error relates back to here according to bluej
allTowns[count].county = countyEntered;
if (continuation == 1) {
loop2 = 1;
System.out.println("please enter the name of a county for which you wish to know the details.");
String countyOfChoice = input.nextLine();
while (loop3 > 0){
if ((allTowns[loop3].county).equals(countyOfChoice)){
System.out.println(allTowns[loop3].name);
System.out.println(allTowns[loop3].population);
loop3 = -2;
}
loop3 = loop3 +1;
}
}
count = count + 1;
}
}
}
答案 0 :(得分:4)
默认情况下,Object
数组中的元素为null
。在尝试访问元素之前初始化元素
for (int i=0; i < allTowns.length; i++) {
allTowns[i] = new CathedralTowns();
}
答案 1 :(得分:0)
这句话非常可疑
allTowns[count] = new CathedralTowns();
在分配长度为50的数组之前,只有一个对象在数组中分配。
CathedralTowns[] allTowns = new CathedralTowns[50];
更不用说如果ArrayIndexOutOfBoundsException
等于或等于count
50
容易出错
然后你开始循环并增加count
及其发生的位置!
你应该遍历整个数组并在每个插槽中分配一个对象。
答案 2 :(得分:0)
NullPointerException发生在“population”而不是“name”是因为“name”字段是静态的,而“population”是非静态的。
还必须按照第一个答案分配CathedralTowns数组。
while (loop2 == 0)
最终会陷入无限循环。如果用户想要输入多个县的详细信息,则此while循环没有结束条件。