3 回答
![?](http://img1.sycdn.imooc.com/533e4d510001c2ad02000200-100-100.jpg)
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 集合,则可以避免再次读取文件。只需将字符串存储在列表中并遍历列表以从中提取元素。
![?](http://img1.sycdn.imooc.com/5458692c00014e9b02200220-100-100.jpg)
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();
}
}
添加回答
举报