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

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

如何從文件(Java)將雙打添加到二維數組中?

如何從文件(Java)將雙打添加到二維數組中?

皈依舞 2021-07-05 12:41:39
我看到的所有示例都涉及在文件開頭指定行數和列數,但我正在使用的方法讀取具有以下內容的文件:1.0 2.03.0 4.0并使用此數據創建一個二維數組并在不指定行數和列數的情況下存儲它。這是我寫的代碼: public static double[][] readMatrixFrom(String file) throws FileNotFoundException {     Scanner input = new Scanner(new FileReader(file));     int rows =0;     int columns =0;     while(input.hasNextLine()){         String line = input.nextLine();         rows++;         columns = line.length();          }     double[][] d = new double[rows][columns]     return d;      }現在我已經創建了二維數組,我不確定如何添加這些值。我試過這個,但得到了一個InputMismatchException.Scanner s1 = new Scanner(file);double[][] d = new double[rows][columns]for (int i= 0;i<rows;i++) {    for (int j= 0;i<rows;j++) {         d[i][j] = s1.nextDouble();     }}
查看完整描述

3 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

如果你只想使用基本數組,你可以用類似的東西來實現它


     Scanner input = new Scanner(new FileReader(file));


     int row=0;

     int col =0;

     String s="";


     //count number of rows

     while(input.hasNextLine()) {

         row++;

         s=input.nextLine();

     }


     //count number of columns

     for(char c: s.toCharArray()) {

         if(c==' ')

             col++;

     }


     col++; // since columns is one greater than the number of spaces


     //close the file

     input.close();


     // and open it again to start reading it from the begining

     input = new Scanner(new FileReader(file));

     //declare a new array

     double[][] d = new double[row][col];   


     int rowNum=0;

     while(input.hasNextLine()) {

         for(int i=0; i< col; i++) {

             d[rowNum][i]= input.nextDouble();

         }

         rowNum++;

     }

但是,如果您更喜歡使用 java 集合,則可以避免再次讀取文件。只需將字符串存儲在列表中并遍歷列表以從中提取元素。


查看完整回答
反對 回復 2021-07-14
?
哈士奇WWW

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

根據您的輸入,您columns = line.length();將返回7而不是2,因為它返回String長度。


因此嘗試計算行中的列數 columns = line.split(" ").length;


此外,在嘗試讀取您的輸入時,您使用i的是第二個索引for-loop。應該是下面這樣


for (int i= 0;i<rows;i++) {

    for (int j= 0;j<columns;j++) {

         d[i][j] = s1.nextDouble();

     }

}


查看完整回答
反對 回復 2021-07-14
  • 3 回答
  • 0 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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