我開始做簡單的閱讀數據文件的練習。當我運行程序時,數據文件會被讀取,而不是,但由於某種原因,我仍然會得到一個「NoSuchElementException」,並且我的輸出沒有以應有的方式格式化。這裏是正在發生的事情:Java:NoSuchElementException
我創建了一個看起來像這樣一個簡單的數據文件:
Barry Burd
Author
5000.00
Harriet Ritter
Captain
7000.00
Ryan Christman
CEO
10000.00
之後,我寫了一個簡單的「吸氣」和「二傳手」的程序(代碼如下)。
import static java.lang.System.out;
//This class defines what it means to be an employee
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;
}
/*The following method provides the method for writing a paycheck*/
public void cutCheck(double amountPaid) {
out.printf("Pay to the order of %s ", name);
out.printf("(%s) ***$", jobTitle);
out.printf("%,.2f\n", amountPaid);
}
}
夠簡單。 然後我寫了實際使用這個東西的程序(下面的代碼)。
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public 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();
}
}
這裏是我的輸出:
Pay to the order of Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at DoPayroll.payOneEmployee(DoPayroll.java:25)
at DoPayroll.main(DoPayroll.java:14)
Barry Burd (Author) ***$5,000.00
Pay to the order of Harriet Ritter (Captain) ***$7,000.00
Pay to the order of Ryan Christman (CEO) ***$10,000.00
編輯我發現了這個問題,但我不明白它大聲笑。顯然,我不得不在數據文件的末尾添加一個空行....爲什麼?
這其實是一個誤導性的解決方案。只要有掃描儀讀取的任何非空白字符,'hasNext()'就會返回true。這可能會或可能不會以回車結束。如果沒有,代碼仍然會進入while循環,異常仍然會被拋出。 – asteri 2012-07-19 19:21:46