我看到的所有示例都涉及到在文件开头指定行数和列数,但我正在使用的方法读取的文件具有以下内容:
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();
}
}
发布于 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集合,则可以避免再次读取该文件。只需将字符串存储在列表中,然后遍历列表以从中提取元素。
https://stackoverflow.com/questions/51804632
复制相似问题