Search code examples
javafileintegerjava.util.scannerinputmismatchexception

InputMismatchException when scanning file of integers


When I run this code, I get an InputMismatchException (see comment). Why does this happen? The file I want to read contains a list of integers separated by spaces.

Below is just the main method.

    public static void main (String[] args) throws Exception {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter file name: ");    
    String fname = in.nextLine();   

    System.out.println("Enter the starting x coordinate: ");
    int x = in.nextInt();
    System.out.println("Enter the starting y coordinate: ");
    int y = in.nextInt();

    Coordinate startPosition = new Coordinate(x, y);

    in.close();

    WaterMesa wm = new WaterMesa(fname);    

    Scanner fs = new Scanner(fname);

    grid_width = fs.nextInt();      // exception occurs here
    grid_height = fs.nextInt();     // and possibly here too?

    int i = 0;
    for (int r = 0; r < grid_width; r++) {  
        for (int c = 0; c < grid_height; c++) {
            i = fs.nextInt();
            grid[r][c] = i; 
            JPanel panel = new JPanel();
            primary.add(panel);

    fs.close();

    wm.canFlowOffMap(startPosition); 
        }
    }
    }

.......................................................................................................................................................


Solution

  • You're scanning the file name string, not the content of the file. Change Scanner fs = new Scanner(fname); to Scanner fs = new Scanner(new File("/path/to/your/files/"+fname));.