以下是我每行读取文本文件行的代码。
ArrayList<Student> studentCollection = new ArrayList<Student>();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("StudentAnswers2.txt"));
String read = null;
while ((read = in.readLine()) != null)
{
read = in.readLine();
String[] splited = read.split(",");
int[] answersTrans = new int[20];
for(int i = 0; i < 20; i++)
{
answersTrans[i] = Integer.parseInt(splited[i+3]);
}
studentCollection.add(new Student(splited[0], splited[1], splited[2], answersTrans));
}
上下文:我试图将每个逗号分隔值设置为学生列表对象的字段(每个学生一行)。前3个值需要作为String参数输入,后面的20个值作为一个int []数组进入。
这里是txt文件的内容:
C97288501,拜恩,约翰,0,3,3,0,2,4,0,1,4,5,0,3,3,1,2,4,2,0,4,5 D11255403,史密斯,艾琳,1,3,2,0,4,3,1,4,5,0,3,3,1,3,4,5,0,5,4,0 C06623662,多伊尔,玛丽,1,4,3,3,2,2,1,1,4,5,3,3,3,5,2,4,2,5,4,5 C02887223,Radecki,杰森,2,4,3,0,2,2,4,1,0,2,3,3,5,0,4,4,0,4,0,5 D11123581,汉利,诺拉,1,0,2,2,3,0,0,1,5,4,3,3,0,3,2,4,0,5,4,4
答案 0 :(得分:3)
删除额外的in.readLine()
,因为您已经在while循环的条件下读取了该行。额外in.readLine()
会导致您跳过每隔一行,并可能导致以下read.split(",")
抛出NullPointerException
,因为您不会检查它是否返回null。
while ((read = in.readLine()) != null)
{
read = in.readLine(); // this extra readLine is wrong
// and should be removed