用戶輸入數字,每行最多20個,最多50行。問題是,如果用戶在一行中輸入少於20個整數,則該數組在空白處填充零,以便總共有20個整數。這會影響我對數組的計算。擺脫二維Java數組中自動填充的零數
有誰知道有效的方法來擺脫這些零,以便只有原始輸入的數字保持?
//Extracting/reading from file
public void readFile(File file) {
try {
//creates scanner to read file
Scanner scn = new Scanner(file);
//set initial count (of rows) to zero
int maxrows = 0;
//sets columns to 20 (every row has 20 integers - filled w zeros if not 20 inputted)
int maxcolumns = 20;
// goes through file and counts number of rows to set array parameter for length
while (scn.hasNextLine()) {
maxrows++;
scn.nextLine();
}
// create array of counted size
int[][] array = new int[maxrows][maxcolumns];
//new scanner to reset (read file from beginning again)
Scanner scn2 = new Scanner(file);
//places integers one by one into array
for (int row = 0; row < maxrows; row++) {
Scanner lineScan = new Scanner(scn2.nextLine());
//checks if row has integers
if (lineScan.hasNextInt()) {
for (int column = 0; lineScan.hasNextInt(); column++) {
array[row][column] = Integer.parseInt(lineScan.next());
}
} else System.out.println("ERROR: Row " + (row + 1) + " has no integers.");
}
rawData = array;
}
}
代碼在哪裏?你如何將整數轉換爲數組中的一行? – Marc
把它看作是一個數組的數組,而不是一個2D數組。只有當你知道它需要多大時才創建每一行。 –
@Marc更新了代碼 –