为什么我的扫描仪将文本文件中的数字作为字符串读取?

问题描述

我有一个文本文件,里面有杂货,然后是它们所在的小岛。出于某种原因,我的扫描仪仅以字符串的形式接收数据,而不是字符串和整数。下面是我的代码,它被超级简化以尝试和排除故障:

public static void readItems(String filename){
    String groceryItem;
    int groceryIsle;
    String specialArea;
    try{
        FileInputStream fis = new FileInputStream(filename);
        Scanner s = new Scanner(fis);
        while (s.hasNext()){
            **System.out.println(s.next());**
        }
    } catch(IOException ex){
        Logger.getLogger(GroceryPlanner.class.getName()).log(Level.SEVERE,null,ex);
        System.out.println("Can not open the file!");
    }
}

这只是打印出所有项目的名称和岛号。当我将代码的突出显示行更改为 s.nextInt() 时,我得到

线程“main”中的异常java.util.InputMismatchException

这里是输入文件片段的链接

enter image description here

我将不胜感激。

解决方法

您可能假设 nextInt 获取下一个 int,但事实并非如此:它 scans the next token of the input as int。如果它找到一个字符串,则会抛出一个 InputMismatchException

由于您的输入以字符串开头,因此会抛出这个确切的异常。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...