Java 我有一个以文件名作为输入的方法,应该返回一个数组作为输出。该文件包含带有科目名称和标记的学生记录
我有一个Student类,在main类中我有一个方法,该方法将文件名(该文件包含带有主题名称和标记的学生记录)作为输入,并返回一个Student数组作为输出 我尝试使用ArrayList,但是我无法将学生记录转换为学生数组。请帮助..下面是我的代码:Java 我有一个以文件名作为输入的方法,应该返回一个数组作为输出。该文件包含带有科目名称和标记的学生记录,java,java-8,Java,Java 8,我有一个Student类,在main类中我有一个方法,该方法将文件名(该文件包含带有主题名称和标记的学生记录)作为输入,并返回一个Student数组作为输出 我尝试使用ArrayList,但是我无法将学生记录转换为学生数组。请帮助..下面是我的代码: public static void main(String[] args) throws FileNotFoundException { String filename = "student.txt"; readData(file
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;
}
}
下面是我得到的错误:
Main.java:28: error: incompatible types: Student cannot be converted to Student[]
return studentR;
^
请尝试以下代码:
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException{
字符串filename=“student.txt”;
读取数据(文件名);
}
私有静态列表readData(字符串文件名)引发FileNotFoundException{
扫描仪输入=新扫描仪(新文件(文件名));
列表<学生>列表=新列表<学生>();
while(input.hasNext()){
String name=input.next();
int physic=input.nextInt();
int chemistry=input.nextInt();
int math=input.nextInt();
Student studentR=新生(姓名、物理、化学、数学);
列表。添加(学生);
系统输出打印项次(列表);
}
用于(学生:列表){
系统输出打印LN(studentR);
}
退货清单;
}
首先,您应该将返回类型更改为List,因为您的数据在ArrayList中,而不仅仅是Array。其次,从同侧for循环返回并不是您想要的,它需要在for循环的外部。最后,在system.out.print中写入对象名不会打印对象,您需要通过访问元素的项(如studentR.name、studentR.marks等)来打印元素可能的重复项,或者您可以让方法返回一个列表:私有静态列表readData(字符串文件名)
@mehsgj首先将列表转换为数组并返回。您可以使用本文了解如何将列表转换为数组。你应该在方法末尾的for循环之后返回它,或者只是将函数的返回类型改为List而不是像George Z说的数组。你不想从循环内部返回。我尝试将列表转换为数组并打印它,但它打印数组地址Student@266474c2 Student@6f94fa3e Student@5e481248 Student@66d3c617 Student@63947c6b Student@2b193f2d Student@355da254 Student@4dc63996 Student@d716361 Student@6ff3c5b5 Student@3764951d Student@4b1210ee Student@4d7e1886 Student@3cd1a2f1 Student@2f0e140b Student@7440e464 Student@49476842 Student@78308db1 Student@27c170f0 Student@5451c3a8Also我应该返回一个学生数组而不是列表
Main.java:28: error: incompatible types: Student cannot be converted to Student[]
return studentR;
^