亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法為本學期的最后一個實驗室正確讀取文件,并且在讀取實際文件時一直遇到問題

無法為本學期的最后一個實驗室正確讀取文件,并且在讀取實際文件時一直遇到問題

阿波羅的戰車 2022-12-15 14:40:40
所以我們有一個實驗室要做,它涉及讀取文件和所有有趣的東西。這是 txt 文件的樣子:Name0221.2Name1222.71Name2193.51Name3183.91Name4201.6Name5191.03Name6183.78Name7193.19Name8182.37Name9211.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
查看完整描述

1 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

您收到NoSuchElementException是因為在對象上調用nextInt()和nextDouble()方法Scanner不會讀取換行符(點擊返回時創建的字符) - 請參閱此答案。


要解決此問題,您可以執行以下操作:


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文件在您的類路徑中。


查看完整回答
反對 回復 2022-12-15
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號