import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private static ArrayList<Countries> arr =null;
static String country;
static String capital;
static String cities;
static String answer;
public static void main(String args[]) throws IOException{
Scanner keybord = new Scanner(System.in);
ArrayList<Countries> d = read("data.txt");
String res = "";
for(int i = 0; i < d.size(); i++){
res += d.get(i).toString();
answer = keybord.nextLine();
if(answer.equalsIgnoreCase(d.get(i).getCapital()))
res+= "The answer is true!";
else
res += "The answer is not true" + "The answer is " + d.get(i).getCapital();
System.out.println(res);
}
}
public static ArrayList<Countries> read(String filename) throws IOException{
Scanner scan = new Scanner(new File(filename));
while(scan.hasNext()){
country = scan.nextLine(); //System.out.println(country);
String cities1 = scan.nextLine(); //System.out.println(cities1);
String cities2 = scan.nextLine(); //System.out.println(cities2);
String cities3 = scan.nextLine(); //System.out.println(cities3);
String cities4 = scan.nextLine(); //System.out.println(cities4);
String capital = scan.nextLine(); //System.out.println(capital);
Countries c = new Countries(cities1, cities2, cities3, cities4, capital);
arr.add(c); // where i get the exception
scan.nextLine();
}
return arr;
}
我不明白为什么在尝试将国家/地区添加到数组列表时出现空指针异常?我不应该在创建它之前将它实例化为 null 吗?