为什么我得到数组的空指针异常?

时间:2012-07-07 19:56:02

标签: java nullpointerexception

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 个答案:

答案 0 :(得分: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();

哪个可能会失败

答案 1 :(得分:0)

您需要初始化arr:

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

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

答案 2 :(得分:0)

未初始化arr变量,替换

private static ArrayList<Countries> arr

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

答案 3 :(得分:0)

您从未初始化arr

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