简体   繁体   English

使用Java中的扫描仪从文件读取文件时出现InputMismatchException

[英]InputMismatchException when reading from a file using Scanner in Java

I need help with this program for school. 我在学校这个程序上需要帮助。 I've been getting this error for a few days now and don't know where the problem is. 我已经收到此错误几天了,不知道问题出在哪里。 I'm reading information from a file, and for some reason i'm getting the following error: 我正在从文件中读取信息,由于某种原因,我遇到以下错误:

ok, so I keep getting the following error in my code: 好的,所以我的代码中不断出现以下错误:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at EmployeeWithFiles.readInputFile(EmployeeWithFiles.java:22)
    at CompanyWithFilesDemo.main(CompanyWithFilesDemo.java:28)

I know the error is in the readInputFile...here's my method to read input: 我知道错误在readInputFile中...这是我读取输入的方法:

public void readInputFile(Scanner inputStream)
{
        setFirstName(inputStream.nextLine());
        setLastName(inputStream.nextLine());
        setNumberOfDependents(inputStream.nextInt());
        setHourlyRate(inputStream.nextDouble());
        setHoursWorked(inputStream.nextDouble());
        setLocalTaxWithheldToDate(inputStream.nextDouble());
        setFederalTaxWithheldToDate(inputStream.nextDouble());
        setStateTaxWithheldToDate(inputStream.nextDouble());

} }

And here's my input file: 这是我的输入文件:

jim
jackson
3
14.50
55.50
515.00
6010.00
2163.00
jim
jackson
3
14.50
55.50
515.00
6010.00
2163.00
jim
jackson
3
14.50
55.50
515.00
6010.00
2163.00

I'm almost positive the problem is occurring from one of the nextInt or nextDouble not carrying to the next line. 我几乎肯定,问题是发生在nextIntnextDouble没有传递到下一行的情况下。 So at some point you may be trying to read a double when it's a string or vice versa. 因此,在某个时候,您可能试图读取双精度型字符串(反之亦然)。 That's where the InputMismatchException occurs. 那就是InputMismatchException发生的地方。

You can avoid this problem by just reading line by line and parsing when necessary. 您可以通过逐行读取并在必要时进行解析来避免此问题。 Make life easier. 让生活更轻松。

setNumberOfDependents(Integer.parseInt(inputStream.nextLine().trim()));
setHourlyRate(Double.parseDouble(inputStream.nextLine().trim()));
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM