I am reading a text file to get the first Int, which is used to set the dimensions of a grid, and then it should read a series of rows of ints to populate that grid. I get the InputMismatchException on the thirdline of numbers. How do I get it to read in the numbers properly?
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");
}
}
I should end up displaying the grid (15 lines of 15 numbers) followed by a count of blobs. The file contains the number 15 on the first line, an empty line, then 15 lines of 15 1's and 0's. I believe it is trying to read each line in as one int, but I am not sure if that's the case.