【问题标题】:InputMismatchException when using Scanner to to read from a file使用 Scanner 从文件中读取时出现 InputMismatchException
【发布时间】:2017-03-06 20:12:56
【问题描述】:

我正在尝试使用扫描仪从 CSV 文件中读取,但是当我尝试读取最后一个双精度并且我的 CSV 文件中是否有不止一行时,我收到了 InputMismatchException。我认为这是因为它正在读取 \n 作为双精度的一部分。如何让它忽略换行符?

CSV 文件

P1,25,30
P2,10,10

Java

public static ArrayList<MarkEntry> readCSV(File file) {
    ArrayList<MarkEntry> entries = new ArrayList<>();
    try
    {
        Scanner in = new Scanner(file).useDelimiter(",");
        while (in.hasNext())
        {
            String title = in.next();
            double mark = in.nextDouble();
            double outOf = in.nextDouble(); //Program Crashes here
            entries.add(new MarkEntry(title, mark, outOf));
        }
    } catch (FileNotFoundException e)
    {
        System.out.println("File: " + file + " not found");
    }

    return entries;
}

【问题讨论】:

  • 只需执行 String[] input = in.nexLIne().split(",") ,然后您将在数组的每个索引中拥有所有值
  • 基于数组中的索引,您可以转换为 Double 或保留为字符串

标签: java csv java.util.scanner inputmismatchexception


【解决方案1】:
    while (in.hasNext())
    {
        String[] inputLine = in.nextLine().split(",");
        //check that the line contains 3 comma seperated values
        if(inputLine.length == 3)
        {
            String title = inputLine[0]; //first on should be P1, p2 etc
            //catch the exception if we are unable to parse the two expected doubls
            try
            {
                double mark = Double.parseDouble(inputLine[1]);
                double outOf = Double.parseDouble(inputLine[2]); //Program Crashes here
                //if we got here then we have valid inputs for adding a MarkEntry
                entries.add(new MarkEntry(title, mark, outOf));
            }catch(NumberFormatException er)
            {
                //print stack trace or something
            }
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多