扫描整数文件时出现 InputMismatchException

InputMismatchException when scanning file of integers

当我 运行 这段代码时,我得到一个 InputMismatchException(见注释)。为什么会这样?我要读取的文件包含一个由空格分隔的整数列表。

下面是主要方法

    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); 
        }
    }
    }

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

您扫描的是文件名字符串,而不是文件内容。将 Scanner fs = new Scanner(fname); 更改为 Scanner fs = new Scanner(new File("/path/to/your/files/"+fname));