用Java读取数组列表和文本文件

问题描述 投票:-1回答:1
public class Student {

    private String name;
    private String courseName;
    private double exam1;
    private double exam2;
    private double exam3;

    public Student(String name, String courseName, double exam1, double exam2, double exam3) {
        this.name = name;
        this.courseName = courseName;
        this.exam1 = exam1;
        this.exam2 = exam2;
        this.exam3 = exam3;
    }
        public String toString() {
        calcGrade();
        String str = "Student: " + name + "\n\tClass Name: " + courseName + "\n\tGrade: " + grade;
        return str;
    }
}

主要:

    public static void main(String[] args) throws IOException {

        Scanner fileIn = new Scanner (new File("students.txt"));
        ArrayList <Student> list = new ArrayList<>();


        while (fileIn.hasNextLine()) {
            list.add(new Student(fileIn.next(), fileIn.next(), fileIn.nextDouble(), fileIn.nextDouble(), fileIn.nextDouble()));
        }
        fileIn.close();
        System.out.println(list.toString());
    }

}

我在这里想念什么?程序无法编译,剩下的是:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ayers_hwk3.Ayers_Hwk3.main(Ayers_Hwk3.java:29)

我对Java编程还是很陌生,这远远超出了我。

java arraylist constructor text-files
1个回答
0
投票

您正在获取此文件,因为文件中可能缺少字段,空格或换行符。因此,当您执行fileIn.next *()时,它将引发NoSuchElementException

相反,您可以执行以下操作。

while (fileIn.hasNextLine()) {
    String line = fileIn.nextLine();
    String[] words = line.split(' ')
    list.add(new Student(words[0], words[1], words[2], words[3], words[4]);
 }

如果这会引发ArrayIndexOutOfBounds异常,然后打印单词并找出错误在文件中的确切位置。

© www.soinside.com 2019 - 2024. All rights reserved.