无法弄清楚java中的NullPointerException错误

时间:2014-10-09 19:53:09

标签: java nullpointerexception

以下是错误:

Exception in thread "main" java.lang.NullPointerException
at CellularData.addCountry(CellularData.java:34)
at CellularData.addCountry(CellularData.java:24)
at TestCSVReader.main(TestCSVReader.java:35)

我一直收到上述错误但似乎无法修复它。我正在读取csv文件并在屏幕上显示数据。基本上,它读取国家,年份和蜂窝数据的统计数据。以下是CellularData类:

public class CellularData {

private Object [][]array;
private int year;

public CellularData(int rows, int columns, int year)
{
    array = new Object[rows+1][columns+1];  //add +1 because initializes the header.
    this.year = year;
    for(int i=1;i<=columns;i++)
    {
    array[0][i] = year++;   //increments the year
    }
}

public void addCountry(String country, double []num)
{
    for(int i=0;i<array.length;i++)
    {    
    if(array[i][0] == null)     //checks if the first row is empty
    {
        //CellularData.addCountry(CellularData.java:24)
        addCountry(country, num, i);  //inserts the data 
        break;
    }
    }
}
private void addCountry(String country, double []num, int row)
{
    array[row][0] = country;
    for(int j = 1;j<array[row].length;j++)
    {
        array[row][j] = num[j-1]; //CellularData.addCountry(CellularData.java:34)
    }
}
public double getNumSubscriptionsInCountryForPeriod(String country, int sYear, int eYear)
{
     double sum = 0;

    for (int i = 1; i < array.length; i++) {

            if (country.equalsIgnoreCase((String) array[i][0])) { //matches with the parameters passed ignoring CAPS
                int start = 1 + sYear - year;   //first index position of the year
                int end = start + (eYear - sYear);  //end position of the year

                if (start >= 0 && end < array[i].length) {   //checks to see if index position is out of bounds

                    for (int k = start; k <= end; k++) {
                        // System.out.println(">> " + country + " adding " + array[i][k]);
                        sum += (Double) array[i][k];   //sum of the stats
                    }
                }
                else {
                    //returns Error messgae and -1
                    System.out.println("ERROR : requested year "+sYear+" from "+ country+" is less than starting year "+this.year);
                    sum = -1;
                    }
            }
            }
    return sum;
    }

public String toString()
{ //prints the array.
    for(Object []a: array)
    {
        for(Object k:a)
        {
            System.out.print(k + "\t");
        }
        System.out.println();
    }
    return " ";
}
    }

这是我的csv阅读器文件,我在这里读取文件:

public class CSVReader {
String[] countryNames;
int[] yearLabels;
double[][] cellularDatatables;
Scanner scan;

public CSVReader(String filename)// throws FileNotFoundException 
{ 
    try{
    File file = new File(filename);
    scan = new Scanner(file);
    scan.nextLine();
    String numLine = scan.nextLine();
    final int n = Integer.parseInt(numLine.split(",")[1]); //Number is the string portion after the first comma

    //Allocate arrays with length n
    countryNames = new String[n];
    cellularDatatables = new double[n][];

    //Read in the header line of years, parse and copy into yearNum
    String[] yearHeaders = scan.nextLine().split(",");
    final int m = yearHeaders.length-1;
    yearLabels = new int[m];
    for(int i=0;i<m;i++)
    {
    yearLabels[i] = Integer.parseInt(yearHeaders[i+1]); //i+1 to skip the first entry in the string arr
    }

   //Now read until we run out of lines - put the first in country names and the rest in the table
   int c = 0;
   while(scan.hasNext())
   {
     String[] inputArr = scan.nextLine().split(",");
     countryNames[c] = inputArr[0];
     cellularDatatables[c] = new double[m];
     for(int i = 0; i < m; i++)
     {
         cellularDatatables[c][i] = Double.parseDouble(inputArr[i+1]);
       }
    }
        scan.close();
    }

    catch(FileNotFoundException e)
    {
        System.out.println(e.getMessage());
    }
}
    public String[] getCountryNames(){
        return countryNames;
    }
    public int[] getYearLabels(){
        return yearLabels;
    }
    public double[][] getParsedTable(){
        return cellularDatatables;
    }
    public int getNumberOfYears()
    {
        return yearLabels.length;
    }
}

还有TestCSVReader文件:

public static void main(String[] args) 
{   
    final String FILENAME = "data/cellular.csv";

    CSVReader parser = new CSVReader(FILENAME);

    String [] countryNames = parser.getCountryNames();
    //System.out.println(countryNames.length);
    int [] yearLabels = parser.getYearLabels();
    //System.out.print(yearLabels.length);
    double [][] parsedTable = parser.getParsedTable();  


    CellularData datatable;
    int numRows = parsedTable.length;
    int numColumns =parser.getNumberOfYears();
    int startingYear = yearLabels[0];
    datatable = new CellularData(numRows, numColumns, startingYear);


    for (int countryIndex = 0; countryIndex < countryNames.length; countryIndex++)
    {
        double [] countryData = parsedTable[countryIndex];
        datatable.addCountry(countryNames[countryIndex], countryData);//Error TestCSVReader.java:35                 
    }


    System.out.printf(countryNames[0] + " (1960 to 2012): %.2f \n", datatable.getNumSubscriptionsInCountryForPeriod(countryNames[0],1960,2012));
    // the output is: Aruba (1960 to 2012): 1170.50 

1 个答案:

答案 0 :(得分:0)

array[row][0] = country;
for(int j = 1;j<array[row].length;j++)
{
    array[row][j] = num[j-1]; //CellularData.addCountry(CellularData.java:34)
}

由于第一行没有给出NullPointerException,我们知道array不为空且array[row]不为空。因此,num必须为null。