扫描整数文件时的InputMismatchException

时间:2015-04-10 03:01:08

标签: java file integer java.util.scanner inputmismatchexception

当我运行此代码时,我得到一个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); 
        }
    }
    }

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

1 个答案:

答案 0 :(得分:0)

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