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)

自闭症网瘾萝莉.ら 提交于 2020-03-24 00:19:38

问题


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

File:

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

回答1:


You should change the delimiter to include optional spaces around commas, and the new line characters as well. Something like this:

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



回答2:


You get the InputMismatchException in int timesBorrowed = scanner.nextInt() for the first line of the input file. The error is caused by the spaces around the comma.

Change the delimiter to *, * then any number of spaces around the comma become part of the delimiter and thus get removed. Instead of the spaces you may also use \\s which covers all whitespaces (space and tabs).

Then you get the exception in line int weight = scanner.nextInt() again for the first line of the input file, because the 1800 is followed by a line break. So what you need is a delimiter which also matches the line breaks: ( *, *)|[\r\n]+

The regular expression means: Either a comma surrounded by any number of spaces or at least one consecutive line break. Note that Unix files have usually only \n while Windows file have usually both characters \r\n in each line break. So that expression covers both file formats and also skips empty lines.

Here is a full example which works:

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



回答3:


The issue here is that your lines are not ending with a comma and there are newlines.

This is what your program is interpreting the first two lines of your input as:

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

Notice how there is no comma after 1800? There is a \n which denotes a newline.

Edit: I'm also noticing spaces after some commas, so that would likely be messing with things also. Try out Eng.Fouad's answer as it addresses my concerns.




回答4:


If you read the file line by line you can add additional checks, e.g. filter out comments (lines starting with "//" in this case):

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


来源:https://stackoverflow.com/questions/60326657/why-is-it-giving-me-an-java-util-inputmismatchexception-when-i-run-this-code-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!