我的扫描仪无法正确访问文本文件的最后一行,因此将文本文件的最后一行存储为全0,而不是实际存在的2D数组。我相信我已经提供了一切内容,可以提供正在发生问题的上下文,但是如果需要更多信息,我可以更新此问题,在此先感谢。
//Creates 2-d array object, stores values from file.
public DominoSort (String fileName) throws java.io.FileNotFoundException{
this.grid = new int [7][8]; //2-d array to hold values from text file
Scanner br = new Scanner(new File(fileName));
String line = br.nextLine();
int r = 0;
int c = 0;
while (br.hasNextLine) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
//this.setS = new ArrayList<>();
//this.pairMappings = new ArrayList<ArrayList<dominoLocation>>();
br.close();
}
//Print grid function, prints out the grid
public void printGrid() {
for(int r = 0; r < this.grid.length; r++) {
System.out.println("");
for(int c = 0; c < this.grid[r].length; c++) {
System.out.print(this.grid[r][c] + " ");
}
}
System.out.println("");
}
//Driver for checking
public static void main(String[] args) throws IOException {
// String line;
//System.out.println(new File(".").getAbsolutePath());
Scanner input = new Scanner(System.in); //get textfile name from user input
System.out.print("Enter the file name: ");
String fileName = input.next();
DominoSort dom = new DominoSort(fileName); //this call populates the 2-d array object
//dom.solvePuzzle(6);
dom.printGrid(); //prints 2d array for output
//dom.solvePuzzle(6);
}
用于测试的文本文件/预期输出:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
2 0 3 2 5 0 5 4 {Notice this line}
实际输出:
3 3 4 2 2 0 0 0
4 6 3 6 3 1 4 1
5 5 4 1 2 1 6 5
5 6 0 2 1 1 5 3
5 4 4 2 6 0 2 6
3 0 4 6 6 1 3 1
0 0 0 0 0 0 0 0 {this line is not right}
您的问题位于嵌套的while / for循环内。在读取所有行之前达到终止条件。 (在读取最后一行之前,nextLine()方法没有更多的行了)。您可以通过在文件的末尾额外添加1或2行,使其显示最后几行来看到此内容。有几种方法可以解决它,其中一种是在while循环之后仅添加一个额外的for循环来分别计算最后一行:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
line = br.nextLine();
r++;
c = 0;
}
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
或者,在第一次运行时不要增加行数:
while (br.hasNextLine()) {
String[] row = line.split("\\s+");
for (String s : row) {
this.grid[r][c] = Integer.parseInt(s);
c++;
}
if (r != 0)
line = br.nextLine();
r++;
c = 0;
}