首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从文件(Java)将双精度数添加到二维数组中?

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

Stack Overflow用户
提问于 2018-08-12 07:50:59
回答 1查看 658关注 0票数 2

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

1.0 2.0
3.0 4.0

并且使用该数据创建2d数组并存储它,而不指定行数和列数。

下面是我写的代码:

 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;      
}

现在我不确定如何添加这些值,因为我已经创建了2d数组。我试过了,但得到了一个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();
     }
}
EN

回答 1

Stack Overflow用户

发布于 2018-08-12 08:08:43

如果你只想使用基本的数组,你可以用下面这样的方法来实现

     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集合,则可以避免再次读取该文件。只需将字符串存储在列表中,然后遍历列表以从中提取元素。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51804632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档