2016-04-20 85 views
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) 

回答

1

你的問題是由於該Scanner使用當前Locale來解析Double所以你需要明確設置Locale,允許使用一個點作爲小數點分隔符,如Locale.US例如事實。因此,要解決你的代碼,你只需要在for循環之前添加到您的代碼如下:

diskScanner.useLocale(Locale.US); 
+0

刪除它,仍然有同樣的問題:( – AlexNikolaev94

+0

奏效,謝謝 – AlexNikolaev94

+0

不客氣! - ) –