我开始学习Java,并且从我的书中做了一些练习。在做一个时,我遇到了这个错误:Exception in thread "main" java.util.InputMismatchException
。我正在编写一个简单的程序,它从.txt
文件中获取数据并将其返回到控制台。这是代码:
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**
来自编译器的错误日志:
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)
答案 0 :(得分:1)
您的问题是由于Scanner
使用当前Locale
来解析Double
,因此您需要明确设置允许使用的Locale
Locale.US
点作为小数分隔符,例如for
。因此,要修复代码,只需在diskScanner.useLocale(Locale.US);
循环之前将其添加到代码中:
last