0
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 吗?

4

4 回答 4

1

你还没有初始化arr,所以默认情况下它是null

初始化它

private static ArrayList<Countries> arr = new ArrayList<Countries>();

还有

您检查下一个元素是否存在

 while(scan.hasNext()){

然后你正在阅读下 7 行

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);

scan.nextLine();

哪个会失败

于 2012-07-07T19:57:35.973 回答
0

您需要初始化 arr:

private static ArrayList<Countries> arr = new ArrayList<Countries>();

如果省略该new ArrayList<Countries>();部分,则默认值为 null,然后当您调用 时arr.add(),您会得到NullPointerException.

于 2012-07-07T19:58:02.947 回答
0

arr 变量未初始化,替换

private static ArrayList<Countries> arr

private static ArrayList<Countries> arr = new ArrayList<Countries>();
于 2012-07-07T19:58:32.133 回答
0

您从未初始化arr.

添加arr = new ArrayList<Countries>();到您的main.

于 2012-07-07T20:00:09.930 回答