gpt4 book ai didi

Java:NoSuchElementException

转载 作者:行者123 更新时间:2023-11-30 06:29:26 26 4
gpt4 key购买 nike

我开始通过简单地读取数据文件来做练习。当我运行该程序时,数据文件被读取但没有读取,但出于某种原因我仍然收到“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

编辑 我发现了问题,但我不明白,哈哈。显然,我不得不在数据文件的末尾添加一个空行....为什么??

最佳答案

I found the problem but I don't understand it lol. Apparently, I had to add a blank line to the end of the data file....why??

因为你是在告诉Scanner输入文件中的salary后面会有一个回车符。但是,对于最后一个条目,没有回车,因此它确定您犯了一个编程错误并抛出一个未经检查的异常。

您可以像这样在您的代码中解决问题:

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();
}
}

关于Java:NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11548956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com