我开始练习简单地阅读一个数据文件。当我运行这个程序时,数据文件会被读取什么的,但是由于某种原因,我仍然得到一个"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编辑我发现了问题,但我不明白。显然,我不得不在数据file....why的末尾添加一个空行?
发布于 2012-07-18 19:48:47
我发现了问题,但我不明白。显然,我不得不在数据file....why的末尾添加一个空行?
因为您正在告诉Scanner,在输入文件中的工资之后将有一个回车返回。但是,对于最后一个条目,没有回车,因此它确定您犯了一个编程错误,并抛出了一个未经检查的异常。
您可以这样解决代码中的问题:
static void payOneEmployee(Scanner aScanner) {
Employee anEmployee = new Employee();
anEmployee.setName(aScanner.nextLine());
anEmployee.setJobTitle(aScanner.nextLine());
anEmployee.cutCheck(aScanner.nextDouble());
if (aScanner.hasNextLine()) {
aScanner.nextLine();
}
}发布于 2012-07-18 19:51:04
每次您调用payOneEmployee()时,都会在最后调用aScanner.nextLine()。这包括您最后一次调用它(当empNum在for循环中等于3时)。当文件中没有新行(\n)并且仍然调用nextLine()时,您收到了一个NoSuchElementException,因为.好吧..。根本没有这样的因素。这是因为文件中的最后一个元素是一个0字符。
为了避免将来发生这种情况,可以添加一个简单的检查器。java.util.Scanner已经为您实现了一个hasNextLine()。因此,您可以简单地更改
aScanner.nextLine();..。敬..。
if(aScanner.hasNextLine()) aScanner.nextLine();发布于 2012-07-18 19:47:33
我认为它已经到了文件的末尾。您应该添加一个while循环:
while(aScanner.hasNext()) {
...
}这样可以防止扫描程序通过文件的末尾。
https://stackoverflow.com/questions/11548956
复制相似问题