gpt4 book ai didi

java - 加载记录时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 04:38:36 25 4
gpt4 key购买 nike

我正在从文件中读取记录并将它们加载到 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;
}
}

最佳答案

在调用方法之前,您需要先调用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]));

关于java - 加载记录时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30464010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com