在本学期的期末实验中无法正确读取文件,并且在读取实际文件时不断遇到问题

问题描述 投票:0回答:1

所以我们有一个实验室要做,其中涉及读取文件和所有有趣的东西。

这就是 txt 文件的样子:

Name0
22
1.2
Name1
22
2.71
Name2
19
3.51
Name3
18
3.91
Name4
20
1.6
Name5
19
1.03
Name6
18
3.78
Name7
19
3.19
Name8
18
2.37
Name9
21
1.01

我发布了应该尝试读取此信息的代码。感谢您的宝贵时间!

我尝试改变一些东西并谷歌搜索异常,但没有运气

    public void readFile()
    {
        //ran intill exception caught
        try
        {
            //finds the student.txt file to read using scanners
            Scanner s = new Scanner("Students.txt");

            while(s.hasNextLine())
            {
                //sets a string name to the first string (First text in 
students is name)
                String name = s.next();
                //looks for a line with a int value and then sets it to 
age
                int age = s.nextInt(); 
                //scans the next line for a double and sets it to gpa

                double gpa = s.nextDouble();
                //creates a new student object and passes what the file 
read into parameters
                Student studentOne = new Student(name , age, gpa);
                //adds new student to array list
                students.add(studentOne);
            }
            s.close();
        }
        // if an exception is caught it will print
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

我相信它应该读取信息并将其存储在受尊重的类别中,因为我们知道它是根据文本文件按此顺序进行的,但是当我运行该方法时,我得到了 java.util.NoSuchElementException

java file exception
1个回答
0
投票

您收到

NoSuchElementException
是因为在
nextInt()
对象上调用
nextDouble()
Scanner
方法不会读取新行字符(按回车键时创建的字符) - 请参阅 this 答案。

要解决此问题,您可以执行以下操作:

public void readFile() throws IOException {
    try (Scanner s = new Scanner(new FileReader(new ClassPathResource("Students.txt").getFile()))) {
        while (s.hasNextLine()) {
            String name = s.nextLine();
            int age = Integer.parseInt(s.nextLine());
            double gpa = Double.parseDouble(s.nextLine());
            Student studentOne = new Student(name, age, gpa);
            students.add(studentOne);
        }
    }
}

注意 - 上面的代码假设

Students.txt
文件位于您的类路径中。

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