如何从文件(Java)将双打添加到二维数组中?

我看到的所有示例都涉及在文件开头指定行数和列数,但我正在使用的方法读取具有以下内容的文件:


1.0 2.0

3.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();

     }

}


皈依舞
浏览 181回答 3
3回答

慕仙森

如果你只想使用基本数组,你可以用类似的东西来实现它&nbsp; &nbsp; &nbsp;Scanner input = new Scanner(new FileReader(file));&nbsp; &nbsp; &nbsp;int row=0;&nbsp; &nbsp; &nbsp;int col =0;&nbsp; &nbsp; &nbsp;String s="";&nbsp; &nbsp; &nbsp;//count number of rows&nbsp; &nbsp; &nbsp;while(input.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;row++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s=input.nextLine();&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;//count number of columns&nbsp; &nbsp; &nbsp;for(char c: s.toCharArray()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(c==' ')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;col++;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;col++; // since columns is one greater than the number of spaces&nbsp; &nbsp; &nbsp;//close the file&nbsp; &nbsp; &nbsp;input.close();&nbsp; &nbsp; &nbsp;// and open it again to start reading it from the begining&nbsp; &nbsp; &nbsp;input = new Scanner(new FileReader(file));&nbsp; &nbsp; &nbsp;//declare a new array&nbsp; &nbsp; &nbsp;double[][] d = new double[row][col];&nbsp; &nbsp;&nbsp; &nbsp; &nbsp;int rowNum=0;&nbsp; &nbsp; &nbsp;while(input.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(int i=0; i< col; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;d[rowNum][i]= input.nextDouble();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;rowNum++;&nbsp; &nbsp; &nbsp;}但是,如果您更喜欢使用 java 集合,则可以避免再次读取文件。只需将字符串存储在列表中并遍历列表以从中提取元素。

哈士奇WWW

根据您的输入,您columns = line.length();将返回7而不是2,因为它返回String长度。因此尝试计算行中的列数 columns = line.split(" ").length;此外,在尝试读取您的输入时,您使用i的是第二个索引for-loop。应该是下面这样for (int i= 0;i<rows;i++) {&nbsp; &nbsp; for (int j= 0;j<columns;j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;d[i][j] = s1.nextDouble();&nbsp; &nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java