【问题标题】:Why is my scanner reading numbers in a text file as a string?为什么我的扫描仪将文本文件中的数字作为字符串读取?
【发布时间】:2020-12-29 22:15:34
【问题描述】:

我有一个文本文件,其中包含杂货项目,然后是它们在文本文件中所在的小岛。出于某种原因,我的扫描仪仅将数据作为字符串而不是字符串和 int 拾取。下面是我的代码,它非常简化,可以尝试排除故障:

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() 时,我得到了

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

这里是输入文件sn-p的链接

我将不胜感激。

【问题讨论】:

  • edit您的问题也包含输入文件的sn-p。
  • 当您使用nextInt() 时,您会尝试从输入文件中读取int 值。但是,您的输入文件也包含文本。
  • @Progman,s.next() 通常抓取整数吗?我以为它只抓住了字符串
  • @TaylorBancroft next() 将返回Scanner 对象的分隔符之间的文本,请参阅docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--
  • @Progman,非常感谢!有时,在进行自己的研究时,只需知道如何提出问题。

标签: java java.util.scanner fileinputstream


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我现在明白了!
猜你喜欢
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多