ユーザーは、行と行ごとに最大20の数値を入力します。問題は、ユーザーが1行に20未満の整数を入力した場合、空のスペースに0が埋められ、合計が20になるということです。これは、配列で行った計算に影響を与えます。2d 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がコードを更新しました –