为了账号安全,请及时绑定邮箱和手机立即绑定

如何从文件(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 关注
  • 180 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信