我正在阅读一个文本文件以获取第一个Int,该Int用于设置网格的尺寸,然后它应读取一系列int行以填充该网格。我在数字的第三行上收到InputMismatchException。如何正确读取数字?
class Grid {
protected int rows;// number of grid rows
protected int cols;// number of grid columns
protected boolean[][] grid;// the grid containing blobs
boolean[][] visited;// used by blobCount
public Grid(String fileName) throws FileNotFoundException {
//reading file using scanner
Scanner sc = new Scanner(new File(fileName));
//first number is the dimension for rows
this.rows = sc.nextInt();
//since it is square matrix second dimension is same as first
this.cols = this.rows;
grid = new boolean[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
//reading from file 1 and 0 if 1 then store true else store false in grid
int number = sc.nextInt();
if (number == 1 )
grid[i][j] = true;
else
grid[i][j] = false;
}
}
public class BlobCountCF {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Enter filename: ");
String fileName = input.nextLine();
Grid grid = new Grid(fileName);
// display grid and blob count
System.out.println(grid);
System.out.println("\nThere are " + grid.blobCount() + " blobs.\n");
}
}
我应该最后显示网格(15行,每行15个数字),然后显示斑点。该文件的第一行包含数字15,一个空行,然后是15行的15个1和0。我相信它正在尝试将每个行读为一个int,但是我不确定是否是这种情况。