它显示空异常。现在该怎么办?
import java.io.File;
import java.util.Scanner;
public class Quiz1 {
public static void main(String[] args) {
File f = new File("QuizMark.txt");
try{
Scanner s = new Scanner (f);
QuizMark[] p = new QuizMark[10];
while(s.hasNext()==true)
{
int c = s.nextInt();
double d = s.nextInt();
for(int i=0;i<10;i++){
p[i]= new QuizMark(c,d);
System.out.println(p[i].getId());
System.out.println(p[i].getScore());
i++;
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
答案 0 :(得分:0)
首先,你的文件必须定义一个保存在其中的数据模式,如标记和id用逗号或连字符下划线等分隔,无论你喜欢保存模式。每个下一个数据应该在下一行。然后阅读正确的文本保存在文件中的方式。
示例QuizMarks.txt
01,96.5
02,78.9
03,65
04,89.7
Java代码
int count = 0;
String s[];
String line="";
QuizMark[] p = new QuizMark[10];
BufferedReader br= new BufferedReader(new FileReader("QuizMark.txt"));
while(line=br.readLine()!=null){
s=line.split(",");//your data separated by symbol in file
//First Record with id and marks
int id =Interger.parseInt(s[0]); //conversion from string to int
double marks = Double.parseDouble(s[1]); //conversion from string to double
p[count]= new QuizMark(id,marks);
count++;
}