[英]Scan in 2D array txt file in Java
當我掃描二維數組文本文件時,如果第一行中沒有數字,則會出現異常錯誤。 我的文本文件如下:
0
8, 3, 5, 4, 1, 6, 9, 2, 7
2, 9, 6, 8, 5, 7, 4, 3, 1
4, 1, 7, 2, 9, 3, 6, 5, 8
5, 6, 9, 1, 3, 4, 7, 8, 2
1, 2, 3, 6, 7, 8, 5, 4, 9
7, 4, 8, 5, 2, 9, 1, 6, 3
6, 5, 2, 7, 8, 1, 3, 9, 4
9, 8, 1, 3, 4, 5, 2, 7, 6
3, 7, 4, 9, 6, 2, 8, 1, 5
頂部的零不應存在。 但是,我發現如果將其取出,我的代碼將無法正常工作。 該數字不必為零,只要有數字就可以與任何數字一起使用。 這是我的代碼:
public static void main(String[] args) throws FileNotFoundException {
String fileName = "Sudoku2d.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\NetBeansProjects\\Sudoku\\Sudoku2d.txt"));
String line = inputStream.nextLine();
int[][] puzzel = new int[9][9];
for (int row = 0; row < 9; row++) {
for (int column = 0; column < 9; column++) {
puzzel[row][column] = Integer.parseInt(line);
}
}
while (inputStream.hasNextLine()) {
line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();
}
這是我的輸出,文本文件頂部為零:
文件Sudoku2d.txt包含以下幾行:
8, 3, 5, 4, 1, 6, 9, 2, 7
2, 9, 6, 8, 5, 7, 4, 3, 1
4, 1, 7, 2, 9, 3, 6, 5, 8
5, 6, 9, 1, 3, 4, 7, 8, 2
1, 2, 3, 6, 7, 8, 5, 4, 9
7, 4, 8, 5, 2, 9, 1, 6, 3
6, 5, 2, 7, 8, 1, 3, 9, 4
9, 8, 1, 3, 4, 5, 2, 7, 6
3, 7, 4, 9, 6, 2, 8, 1, 5
BUILD SUCCESSFUL (total time: 0 seconds)
如果刪除頂部的零,則會出現以下錯誤:
Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at array.Array.main(Array.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
我不想在我的文本文件的頂部放置隨機數以使其運行。 誰能告訴我為什么會這樣?
如果刪除第一行,則會出現錯誤,因為只有第一行進入了數組(您的2D數組由第一行中的單個數字填充)。 因此,如果刪除第一行,則Integer.parseInt()
在文本文件中命中逗號,並引發異常。
您需要更改代碼,以便將文本文件的內容放入數組中,一種方法是使用while循環將文本文件的內容放入數組中:
String fileName = "Sudoku2d.txt";
Scanner inputStream = null;
String[] line;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\NetBeansProjects\\Sudoku\\Sudoku2d.txt"));
int[][] puzzel = new int[9][9];
int row = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine().split(",");
for (int i = 0; i < 9; i++) {
puzzel[row][i] = Integer.parseInt(line[i]);
}
row++;
}
您可以使用以下代碼來檢查2D數組中的數據:
for (int i = 0; i < 9; i++) {
System.out.println(Arrays.toString(puzzel[i]));
}
如果使用當前代碼運行此命令,則將看到數組僅在第一行填充數字。 如果更改為我的代碼,它將顯示文本文件中的數據已正確進入數組(一旦刪除了第一行中的那個數字)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.