[英]Getting integer values to array from file
我正在嘗試通過從文件中分隔的逗號獲取 integer 值並將它們放入二維數組中。 文件是這樣的;
0,7,9,0,0,14
7,0,10,15,0,0
9,10,0,11,0,2
0,15,11,0,6,0
0,0,0,6,0,9
14,0,2,0,9,0
所以我希望第一行位於數組 [0] [0 到 5] 中,其他行也相同,例如數組 [2] [1] 必須為 10。但我無法弄清楚二維數組的算法在這里。
public static void main(String[] args) throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
Scanner sc = new Scanner(reader);
int[][] array = new int[6][6];
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] str = line.split(",");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
array[i][j] = Integer.valueOf(str[i]);
}
}
}
}
您正在遍歷每一行的每個值。 您的索引之一需要是行,另一個需要是行內的 position。 你只需要一個for
循環; 您應該增加另一個索引作為您的 while 循環的一部分。
public static void main(String[] args) throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
Scanner sc = new Scanner(reader);
int[][] array = new int[6][6];
int i=0;
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] str = line.split(",");
for (int j = 0; j < 6; j++) {
array[i][j] = Integer.valueOf(str[j]);
}
i++;
}
}
您還應該考慮,如果文件超過 6 行或超過 6 行,這將失敗,因此這不是非常健壯的代碼。 完成讀取文件后,最好填充不同的(動態)數據類型並轉換為數組。 至少,您應該檢查您沒有超出指數的預期范圍。
你可以這樣做。 關鍵是Java中沒有真正的多維arrays。 只需單個 D arrays 也可以容納 arrays。
// allocate the "2D" array but no need to specify the rows.
int[][] array = new int[6][];
// starting row number
int rowNumber = 0;
while(sc.hasNextLine()){
String line = sc.nextLine();
System.out.println(line);
String[] str = line.split(",");
// here is where your code differs
// allocate a new row based on length of items just read
int[] row = new int[str.length];
// Now copy and convert to ints.
for (int i = 0; i < str.length; i++) {
row[i] = Integer.parseInt(str[i]);
}
// Then just assign the row to the row number.
// you can do this because a two dimentional array is just an
// one dimenional array of another one dimensional array.
array[rowNumber++] = row;
}
// print them out for verification.
// get each row (from the array of rows)
for (int[] row : array) {
System.out.println(Arrays.toString(row));
}
所以做了什么就像下面這樣;
int [][] matrix = new int[2][];
matrix[0] = new int[]{1,2,3,4};
// rows can be different sizes.
matrix[1] = new int[]{1,2,3,4,5,6,7};
for (int i = 0; i <2; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
System.out.print(row[j] + " " );
}
System.out.println(); // next line
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.