데이터 파일을 읽는 것만으로 연습을 시작합니다. 프로그램을 실행하면 데이터 파일이 읽히고 읽히지 않습니다. 그러나 어떤 이유로 든 여전히 "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);
}
}
쉽습니다. 그 다음 나는이 물건을 실제로 사용하는 프로그램을 썼다 (아래 코드).
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
편집 내가 문제를 발견하지만 난 롤을 이해하지 않습니다
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();
}
}
여기 내 출력됩니다. 분명히, 나는 데이터 파일의 끝에 빈 줄을 추가해야했다 .... 왜?
이 실제로 오해의 소지 솔루션입니다 ...
...로 변경할 수 있습니다. 'hasNext()'는 Scanner가 읽을 수있는 공백이 아닌 문자가있는 한 true를 반환합니다. 이것은 캐리지 리턴으로 끝날 수도 있고 끝나지 않을 수도 있습니다. 그렇지 않으면 코드는 여전히 'while'루프를 입력하고 Exception은 여전히 throw됩니다. – asteri