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

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

Java - 將數據從txt文件傳輸到數組中

Java - 將數據從txt文件傳輸到數組中

瀟湘沐 2024-01-25 23:01:40
我目前正在嘗試開發一個程序,該程序使用學生 ID 和 GPA(取自 txt 文件),并使用它們來做許多其他事情,例如根據 GPA 范圍將學生分為 8 個類別之一,制作學生的直方圖并按 GPA 對學生進行排名。然而,我需要做的第一件事是將學生 ID 和 GPA 轉移到兩個單獨的數組中。我知道創建數組的語法如下:elementType[] arrayRefVar = new elementType[arraySize]但是,我仍然不知道如何將從文件讀取的數據傳遞到兩個單獨的數組中。我必須從txt文件中讀取數據的代碼如下:public static void main(String[] args) throws Exception  // files requires exception handling{    String snum;         double gpa;    Scanner gpadata = new Scanner(new File("studentdata.txt"));    while (gpadata.hasNext()) // loop until you reach the end of the file     {        snum = gpadata.next(); // reads the student's id number        gpa = gpadata.nextDouble(); // read the student's gpa        System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window    }}所以我的問題是:如何將此信息傳遞到兩個單獨的數組中?如果我的問題很難理解,我很抱歉,我對編程非常陌生。我已經被這個程序困擾很長時間了,任何幫助將非常感激!謝謝。
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

您可以在 while 循環之前創建兩個數組,然后將循環內的每個元素添加到每個數組中。但這種方法有一個問題:我們不知道值的數量,因此我們無法為此創建固定大小的數組。我建議改為使用ArrayList,它可以根據需要增長。像這樣的東西:


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


    Scanner gpadata = new Scanner(new File("studentdata.txt"));

    List<String> IDs = new ArrayList<>();

    List<Double> GPAs = new ArrayList<>();

    while (gpadata.hasNext()) // loop until you reach the end of the file

    {

        String snum = gpadata.next(); // reads the student's id number

        double gpa = gpadata.nextDouble(); // read the student's gpa


        IDs.add(snum);

        GPAs.add(gpa);


        System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window

    }

    // Use IDs and GPAs Lists for other calculations

}

更好的方法是使用MapGPA 與學生 ID“配對”。


編輯:


在您澄清最大記錄數永遠不會超過 1000 后,我修改了我的解決方案以使用數組而不是列表。我沒有更改變量名稱,因此您可以輕松比較解決方案。


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


    Scanner gpadata = new Scanner(new File("studentdata.txt"));

    String[] IDs = new String[1000];

    double[] GPAs = new double[1000];

    int counter = 0;


    while (gpadata.hasNext()) // loop until you reach the end of the file

    {

        String snum = gpadata.next(); // reads the student's id number

        double gpa = gpadata.nextDouble(); // read the student's gpa


        IDs[counter] = snum;

        GPAs[counter] = gpa;


        System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window

        counter++;

    }

    // Use IDs and GPAs Lists for other calculations

}

請注意,我們需要一個counter(又名索引)變量來尋址數組槽。


查看完整回答
反對 回復 2024-01-25
  • 1 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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