加载记录时的NullPointerExeption

时间:2015-05-26 16:24:03

标签: java nullpointerexception

我正在从文件中读取记录并将它们加载到GameRecord数组中。

单个记录由name(String)level(int)和score(int)组成。

该文件包含这些记录,每条记录在一行上,而字段由一个标签分隔。

我在第

行收到nullPointerException
 g[j].setName(rec[0]);

这是我的计划。

 import java.io.*;
 import java.util.*;
 class FIO
 {
  public static void main(String []args)throws IOException
  {

  FileReader r =new FileReader("records.txt");

  GameRecord []g=loadGameRecord(r);



  }
  public static GameRecord[] loadGameRecord(FileReader reader) 
  {

   //at most 30 records in file

    Scanner s =new Scanner(reader);
    String []arr=new String [30];
    int i=0;
    while(s.hasNextLine())
    {  
     arr [i++]=s.nextLine();
    }

    GameRecord []g=new GameRecord[i];
    String []rec;
    for(int j = 0;j < i;++j)
    {
     rec=arr[j].split("\t");


     g[j].setName(rec[0]);
     g[j].setLevel(Integer.parseInt(rec[1]));
     g[j].setScore(Integer.parseInt(rec[2]));
    }
    return g;

  }
 }


 class GameRecord
 {
  int level;
  int score;
  String name;

  public void setName(String n)
  {
   this.name = n;
  }  
  public void setScore(int s)
  {
   this.score = s;
  }
  public void setLevel(int l)
  {
   this.level = l;
  }
  public String getName()
  {
   return this.name;
  }  
  public int getScore()
  {
   return this.score;
  }
  public int getLevel()
  {
   return this.level; 
  }
 }  

2 个答案:

答案 0 :(得分:2)

在调用方法之前,您需要调用g[j] = new GameRecord();

目前看来,你试图在空对象上调用你的函数(因此是NPE)。正如Trobbins指出的那样,仅仅因为你制作了一系列新的GameRecords并不意味着你已经制作了任何GameRecords。它只是意味着你已经创造了存储游戏记录的空间。

虽然如果是这种情况,最好让构造函数接受一个字符串和2个整数

例如:

// set the values in the constructor. 
public GameRecorder(String name, int level, int score) {
    this.name = name;
    this.level = level;
    this.score = score;
}

您可以使用

调用此构造函数
g[j] = new GameRecord(rec[0], Integer.parseInt(rec[1]), Integer.parseInt(rec[2]));

答案 1 :(得分:0)

您刚刚创建了一个GameRecord数组g,要开始使用它,您需要初始化数组中的条目。 你应该在循环内部。

for(int j = 0;j < i;++j)
{
 rec=arr[j].split("\t");

 g[j] = new GameRecord();
 g[j].setName(rec[0]);
 g[j].setLevel(Integer.parseInt(rec[1]));
 g[j].setScore(Integer.parseInt(rec[2]));
}

来自jls

A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array.