我开始通过简单地读取数据文件来做练习。当我运行程序时,数据文件被读取,但由于某种原因,我仍然得到“NoSuchElementException”,并且我的输出没有按照预期的方式格式化。这是发生了什么:
我创建了一个简单的数据文件,如下所示:
Barry Burd
Author
5000.00
Harriet Ritter
Captain
7000.00
Ryan Christman
CEO
10000.00
之后,我编写了一个简单的“getter”和“setter”程序(代码如下)。
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
编辑 我发现了问题,但我不明白,哈哈。显然,我必须在数据文件的末尾添加一个空行......为什么?