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 集合,則可以避免再次讀取文件。只需將字符串存儲在列表中并遍歷列表以從中提取元素。

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();
}
}
添加回答
舉報