java - 从文件读取时输入不匹配

标签 java java.util.scanner inputmismatchexception

我有一个文件,其数据组织如下:

现代圣达菲

2005 16999 8

水星登山者全轮驱动

2004 17999 7.5

水星大侯爵

2006 19999 12.5

第一行是汽车名称,下一行是年份、价格和折扣金额。我正在尝试读取包含许多这样的行的文件,但最重要的是价格和折扣并不总是以双倍形式表示。

这是我编写的一段代码,但没有正确解析这些代码行。我收到输入不匹配异常。

我做错了什么?

try {

         Scanner scanFile = new Scanner(file);
         while(scanFile.hasNext()) {   

            String carName = scanFile.nextLine();

            int year = scanFile.nextInt();
            double listPrice = scanFile.nextDouble();
            double percentDiscount = scanFile.nextDouble();

            double discountAmount = calculateDiscount(listPrice, percentDiscount);
            double netPrice = calculateNetPrice(listPrice, discountAmount);

            carList.add(new Proj1CarData(carName, year, listPrice, percentDiscount, discountAmount, netPrice));

         }
      } catch(FileNotFoundException fnfe) {
            System.out.println("Unable to locate the file supplied.");
      }

最佳答案

nextLine() 定义为

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

意味着nextLine()将从当前位置读取到行分隔符。

首次调用 double percentDiscount = scanFile.nextDouble(); 后,扫描仪的光标位于 2005 16999 8 行中的第 8 行之后。

在循环的第二次迭代中,String carName = scanFile.nextLine(); 将读取一个空字符串,因为 8 和行分隔符之间没有字符串。然后,intyear = scanFile.nextInt(); 抛出 InputMismatchException,因为光标现在正在查看 Mercury Mountaineer AWD

我不知道我是否能够很好地解释自己。

要解决此问题,简化版本只需在循环末尾添加额外的 nextLine() 调用即可:


String carName = scanFile.nextLine();

int year = scanFile.nextInt();
double listPrice = scanFile.nextDouble();
double percentDiscount = scanFile.nextDouble();
scanFile.nextLine();

我认为处理此问题的更好方法是使用 nextLine() 读取每一行,并检查该行是否是 carname 或年份/价格/折扣信息。

希望这有帮助。

关于java - 从文件读取时输入不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579142/

相关文章:

java - 尽管我有一个 Eclipse 要求返回声明

java - 如何在java中处理来自Apache Spark Streaming的Json数据

java - 输入不匹配异常错误 学生成绩和姓名

java - "Exception in thread "主要 "java.util.InputMismatchException"**

java - Java 中是否有一个函数允许您将字符串转换为 Int ,考虑到字符串中包含您想要忽略的字符?

java - 使用扫描仪读取 csv 文件值,useDelimiter (";")不起作用

java - 代码不久前工作然后 "java.util.InputMismatchException"

java - Java OOP 中的消息传递是什么意思?

java - 禁止从 java 中的 jar 文件中提取

java - Spring MVC : Bad request (parameter missing) on file upload even when required parameters are present