当我使用带有文本的文本文件(如下所示)时,当我 运行 这段代码时,为什么它给我一个 java.util.InputMismatchException

why is it giving me an java.util.InputMismatchException when i run this code when I use a text file with the text (shown underneath)

import java.util.*;

public void readToolData(String fileName) throws FileNotFoundException
{
    File dataFile = new File(fileName);
    Scanner scanner = new Scanner(dataFile);
    scanner.useDelimiter(",");

    while( scanner.hasNext() )
    {
        String toolName = scanner.next();
        String itemCode = scanner.next();
        int timesBorrowed = scanner.nextInt();
        boolean onLoan = scanner.nextBoolean();
        int cost = scanner.nextInt();
        int weight = scanner.nextInt();
        storeTool(new Tool(toolName, itemCode, timesBorrowed, onLoan, cost, weight));
    }

    scanner.close();
}

文件:

Makita BHP452RFWX,RD2001, 12 ,false,14995,1800
Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200
DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
Bosch GSR10.8-Li Drill Driver,RD3021,25, true,9995,820
Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200
DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300
Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400

这里的问题是你的行没有以逗号结尾并且有换行符。

这就是您的程序将输入的前两行解释为:

Makita BHP452RFWX,RD2001, 12 ,false,14995,1800\nFlex Impact Screwdriver FIS439,RD2834,14,true,13499,1200

注意1800后面怎么没有逗号了?有一个 \n 表示换行符。

编辑:我还注意到一些逗号后有空格,所以这也可能会弄乱事情。试试 Eng.Fouad 的回答,因为它解决了我的顾虑。

您应该更改分隔符以包括逗号周围的可选空格,以及换行符。像这样:

scanner.useDelimiter("(\s*,\s*)|(\r\n)|(\n)");

您在 int timesBorrowed = scanner.nextInt() 中得到输入文件第一行的 InputMismatchException。错误是由逗号周围的 space 引起的。

将分隔符更改为 *, *,然后逗号周围的任意数量的 space 将成为分隔符的一部分,从而被删除。除了 space,您还可以使用 \s,它涵盖所有白色 space(space 和制表符)。

然后你在输入文件的第一行再次在行 int weight = scanner.nextInt() 中得到异常,因为 1800 后面跟着一个换行符。所以你需要的是一个也匹配换行符的分隔符:( *, *)|[\r\n]+

正则表达式表示:由任意数量的 space 包围的逗号或至少一个连续的换行符。请注意,Unix 文件通常只有 \n 而 Windows 文件通常在每个换行符中都有两个字符 \r\n。因此该表达式涵盖两种文件格式并跳过空行。

这是一个完整的例子:

public class Main
{

    public static void readToolData(String fileName) throws FileNotFoundException
    {
        File dataFile = new File(fileName);
        Scanner scanner = new Scanner(dataFile);
        scanner.useDelimiter("( *, *)|[\r\n]+");
        while (scanner.hasNext())
        {
            String toolName = scanner.next();
            String itemCode = scanner.next();
            int timesBorrowed = scanner.nextInt();
            boolean onLoan = scanner.nextBoolean();
            int cost = scanner.nextInt();
            int weight = scanner.nextInt();
            System.out.println("toolName=" + toolName + ", weight=" + weight);
        }
        scanner.close();
    }

    public static void main(String[] args) throws FileNotFoundException
    {
        readToolData("/home/stefan/Programmierung/PC-Java/test/src/test.txt");
    }
}

如果您逐行阅读文件,您可以添加额外的检查,例如过滤掉评论(在这种情况下以“//”开头的行):

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main
{

    public static void readToolData(String fileName) throws FileNotFoundException
    {
        File dataFile = new File(fileName);
        Scanner scanner = new Scanner(dataFile);
        while (scanner.hasNext())
        {
            String line = scanner.nextLine().trim();
            if (line.isEmpty() || line.startsWith("//"))
            {
                // skip this line
                continue;
            }

            // Split the line
            String[] parts = line.split(" *, *");

            String toolName = parts[0];
            String itemCode = parts[1];
            int timesBorrowed = Integer.parseInt(parts[2]);
            boolean onLoan = Boolean.parseBoolean(parts[3]);
            int cost = Integer.parseInt(parts[4]);
            int weight = Integer.parseInt(parts[5]);

            System.out.println("toolName=" + toolName + ", weight=" + weight);
        }
        scanner.close();
    }

    public static void main(String[] args) throws FileNotFoundException
    {
        readToolData("/home/stefan/Programmierung/PC-Java/test/src/test.txt");
    }
}