So I'm having trouble looping through a .txt file formatted as such:
31718 PHILLIP LENNOX 55.0 20.00
11528 NANCY TROOPER 40,0 10.45
16783 JOHN CONNAUGHT 30.5 10.00
10538 PETER DUNCAN 45.0 10.75
21O15 JAMES HAROLD 32.0 10.50
61326 HARRY KUHN 25.0 12.30
Now I know there's purposively errors inside of the .txt file, and that's where my catch (InputMismatchException n)
comes into play. I'm supposed to pick up any mismatch in the .txt file and be able to store it inside another .txt file.
The part where I'm stuck at is I can't seem to figure out a loop outside of my try/catch method to successfully continue to look through the .txt file after an InputMismatchException
is found...
I have tried a for-loop, but setting int i = 0;
basically doesn't even start my program since the Arraylist ArrEmployee is of size null
? (From what I understand of Java)
Here's my code (Where is your Windows user name):
public class Main {
public static void main(String[] args) {
ArrayList<Employee> ArrEmployee = new ArrayList<Employee>(); // array for employee objects
try {
Scanner txtIn = new Scanner(new File("/Users/<USER>/Documents/workspace/COMP 249 - Assignment 3/src/payroll.txt"));
while (txtIn.hasNext()) { // looping through the payroll.txt file and creating Employee objects from its data
long EmployeeNumber = txtIn.nextLong();
String EmployeeName = txtIn.next();
String LastName = txtIn.next();
double HoursWorked = txtIn.nextDouble();
double HourlyWage = txtIn.nextDouble();
ArrEmployee.add(new Employee(EmployeeNumber, EmployeeName, LastName, HoursWorked, HourlyWage));
}
} catch (FileNotFoundException e) {
System.out.println("File payroll.txt was not found.");
} catch (InputMismatchException n) {
if (ArrEmployee.get().getHourlyWage() < 10.35) {
System.out.println("Hourly wage under minimum");
}
}
}
}
Your main error as I see it is that you have your while loop inside of your line-reading try/catch block, and so there's no way to recover back to the loop when you run into an error.
Instead:
fileScanner
, while (fileScanner.hasNextLine())
fileScanner.nextLine()
. lineScanner
, ie, Scanner lineScanner = new Scanner(line);
In pseudocode
Using try with resources get File and create fileScanner Scanner object
while fileScanner has next line
create String line from fileScanner's next line.
try with resources, create lineScanner using line
parse each token in line using lineScanner.
...
...
Create Employee instance with information obtained above
place into ArrayList.
catch input mismatch here
send line to error File
end while fileScanner has next line
catch File not found
Would seem that you want to read the file line by line, and then attempt to parse each line with try {} catch {} to catch format errors. Then each line could be written to a separate errors file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.