我对 Java 和编程非常陌生,并且正在从事一个类项目,我们正在学习 i/o、数组和对象,并且我们有一些非常具体的指导方针要遵循。当编译器到达“countryInfo[count].setName(name);”时 ,它给了我
Main.main(Main.java:53) 处的线程“main”java.lang.NullPointerException 中的异常
如果我将其注释掉,下一行会给我同样的错误。我确信有更有效的方法来重新编写这段代码,但由于我们是新手,我们不允许这样做。在我问之前,我读了很多关于 Null 异常的内容……如果我在某个地方错过了它,我深表歉意。我迷路了 :(
public class Main {
/**
* @param args the command line arguments
*/
private static Country[] countryInfo = new Country[43];
public static void main(String[] args) throws IOException {
String name = "";
String capital = "";
String region = "";
int region_Nbr = 0;
int capital_population = 0;
// TODO code application logic here
String filename = "Countries.txt";
String inputString;
FileInputStream fis1 = new FileInputStream(filename);
BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1));
inputString = br1.readLine();
while (inputString != null) {
int count = 0;
System.out.print(inputString + "\n");
name = inputString.substring(0, 13).trim();
//System.out.print(name + ", "); //echo
capital = inputString.substring(24, 36).trim();
//System.out.print(capital + ", ");//echo
region = inputString.substring(40, 56).trim();
//System.out.print(region + ", "); //echo
region_Nbr = Integer.parseInt(inputString.substring(64, 66).trim());
//System.out.print(region_Nbr + ", ");//echo
capital_population = Integer.parseInt(inputString.substring(72, inputString.length()).trim());
//System.out.print(capital_population + "\n");
countryInfo[count].setName(name);
countryInfo[count].setCapital(capital);
countryInfo[count].setRegion(region);
countryInfo[count].setRegionNum(region_Nbr);
countryInfo[count].setPopulation(capital_population);
inputString = br1.readLine();
count++;
} //end while
}
}
public class Country {
private String name;
private String capital;
private String region;
private int region_Nbr;
private int capital_population;
public void setName(String w) {
this.name = w;
} //end get name