I’m beginning to do exercises with simply reading in a data file. When I run the program, the data file gets read and what not, but for some reason I still get a “NoSuchElementException” and my output is not formatted the way it is supposed to be. Here is what is going on:
I created a simple data file that looks like this:
Barry Burd
Author
5000.00
Harriet Ritter
Captain
7000.00
Ryan Christman
CEO
10000.00
After that I wrote a simple “getter” and “setter” program (code is below).
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);
}
}
Easy enough. Then I wrote the program that actually uses this stuff (code below).
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();
}
}
Here is my output:
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
EDIT 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??
Because you are telling the
Scannerthat there will be a carriage return after the salary in the input file. However, for the last entry, there was no carriage return and so it determined that you had made a programming error and threw an unchecked exception.You could solve the problem in your code like so: