user3384292
user3384292

Reputation: 5

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:

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

Upvotes: 0

Views: 209

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209052

I'm almost positive the problem is occurring from one of the nextInt or nextDouble not carrying to the next line. 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.

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

Upvotes: 1

Related Questions