3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果你只想使用基本數(shù)組,你可以用類似的東西來(lái)實(shí)現(xiàn)它
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 集合,則可以避免再次讀取文件。只需將字符串存儲(chǔ)在列表中并遍歷列表以從中提取元素。

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
根據(jù)您的輸入,您columns = line.length();將返回7而不是2,因?yàn)樗祷豐tring長(zhǎng)度。
因此嘗試計(jì)算行中的列數(shù) columns = line.split(" ").length;
此外,在嘗試讀取您的輸入時(shí),您使用i的是第二個(gè)索引for-loop。應(yīng)該是下面這樣
for (int i= 0;i<rows;i++) {
for (int j= 0;j<columns;j++) {
d[i][j] = s1.nextDouble();
}
}
添加回答
舉報(bào)