我有一个 Student 类,在主类中我有一个方法,该方法采用 fileName(该文件包含带有科目名称和分数的学生记录)作为输入,并返回一个 Student 数组作为输出。
我尝试使用 ArrayList,但是我无法将学生的记录转换为学生数组。请帮助..下面是我的代码:
public static void main(String[] args) throws FileNotFoundException {
String filename = "student.txt";
readData(filename);
}
private static Student[] readData(String filename) throws FileNotFoundException{
Scanner input = new Scanner(new File(filename));
ArrayList<Student> list = new ArrayList<Student>();
while(input.hasNext()){
String name = input.next();
int physic = input.nextInt();
int chemistry = input.nextInt();
int math = input.nextInt();
Student studentR = new Student(name,physic,chemistry,math);
list.add(studentR);
System.out.println(list);
}
for (Student studentR : list) {
System.out.println(studentR);
return studentR;
}
}
我的文本文件如下所示:
Amy 85 95 78
Nancy 83 93 82
Richard 81 91 86
Daniel 77 78 79
James 80 90 85
Cathy 95 74 89
Paul 84 87 79
以下是我收到的错误:
Main.java:28: error: incompatible types: Student cannot be converted to Student[]
return studentR;
^
最佳答案
试试这个代码:
public static void main(String[] args) throws FileNotFoundException {
String filename = "student.txt";
readData(filename);
}
private static List < Student > readData(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new File(filename));
List < Student > list = new List < Student > ();
while (input.hasNext()) {
String name = input.next();
int physic = input.nextInt();
int chemistry = input.nextInt();
int math = input.nextInt();
Student studentR = new Student(name, physic, chemistry, math);
list.add(studentR);
System.out.println(list);
}
for (Student studentR: list) {
System.out.println(studentR);
}
return list;
}
关于java - 我有一个以文件名作为输入的方法,应该返回一个数组作为输出。该文件包含带有科目名称和分数的学生记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58143999/