1
我開始學習Java,我正在從我的書中做一些練習。當做一個,我遇到了這個錯誤:Exception in thread "main" java.util.InputMismatchException
。我正在編寫一個簡單的程序,它從.txt
文件獲取數據並將其返回到控制檯。下面的代碼:Java拋出InputMismatchException
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)
刪除它,仍然有同樣的問題:( – AlexNikolaev94
奏效,謝謝 – AlexNikolaev94
不客氣! - ) –