第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

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

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

皈依舞 2021-07-05 12:41:39
我看到的所有示例都涉及在文件開(kāi)頭指定行數(shù)和列數(shù),但我正在使用的方法讀取具有以下內(nèi)容的文件:1.0 2.03.0 4.0并使用此數(shù)據(jù)創(chuàng)建一個(gè)二維數(shù)組并在不指定行數(shù)和列數(shù)的情況下存儲(chǔ)它。這是我寫(xiě)的代碼: 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;      }現(xiàn)在我已經(jīng)創(chuàng)建了二維數(shù)組,我不確定如何添加這些值。我試過(guò)這個(gè),但得到了一個(gè)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貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊

如果你只想使用基本數(shù)組,你可以用類似的東西來(lái)實(shí)現(xiàn)它


     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 集合,則可以避免再次讀取文件。只需將字符串存儲(chǔ)在列表中并遍歷列表以從中提取元素。


查看完整回答
反對(duì) 回復(fù) 2021-07-14
?
哈士奇WWW

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊

根據(jù)您的輸入,您columns = line.length();將返回7而不是2,因?yàn)樗祷豐tring長(zhǎng)度。


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


此外,在嘗試讀取您的輸入時(shí),您使用i的是第二個(gè)索引for-loop。應(yīng)該是下面這樣


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

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

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

     }

}


查看完整回答
反對(duì) 回復(fù) 2021-07-14
  • 3 回答
  • 0 關(guān)注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)