Reputation: 1209
I started to learn Java and I'm doing some exercises from my book. While doing one, I faced this error: Exception in thread "main" java.util.InputMismatchException
. I'm writing a simple program which takes data from the .txt
file and returns it to the console. Here's the code:
Employee.java
:
import static java.lang.System.out;
public class Employee {
private String name;
private String jobTitle;
public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}
public void setJobTitle(String jobTitleIn) {
jobTitle = jobTitleIn;
}
public String getJobTitle() {
return jobTitle;
}
public void cutCheck(double amountPaid){
out.printf("Pay an employee %s ", name);
out.printf("(%s) ***$", jobTitle);
out.printf("%,.2f", amountPaid);
}
}
DoPayroll.java
:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class DoPayroll {
public static void main(String[] args) throws IOException {
Scanner diskScanner = new Scanner(new File ("EmployeeInfo.txt"));
for(int empNum = 1; empNum <= 3; empNum++){
payOneEmployee(diskScanner);
}
}
static void payOneEmployee(Scanner aScanner) {
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
aScanner.nextLine();
}
}
EmployeeInfo.txt
:
John
Manager
15000.00
Alice
Secretary
8000.00
Bob
Engineer
12000.00
**an empty line**
error log from compiler:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at DoPayroll.payOneEmployee(DoPayroll.java:19)
at DoPayroll.main(DoPayroll.java:11)
Upvotes: 1
Views: 463
Reputation: 44965
Your problem is due to the fact that the Scanner
uses the current Locale
to parse a Double
so you need to explicitly set a Locale
that allows to use a dot as decimal separator such as Locale.US
for example. So to fix your code, you simply need to add this into your code before the for
loop:
diskScanner.useLocale(Locale.US);
Upvotes: 1