简体   繁体   中英

For loop for ArrayList in java

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:

  • yes do your file obtaining try / catch (FileNotFoundException ...) first and have all the rest of your code inside of this.
  • Then do your while loop
  • Then inside your while loop catch for InputMismatchException.
  • Myself, I'd use a Scanner based on the File, say named, fileScanner ,
  • And my while loop would loop while (fileScanner.hasNextLine())
  • First line inside the while loop, I'd extract the whole line by calling fileScanner.nextLine() .
  • I'd then create a 2nd Scanner inside the while loop based on the line obtained, perhaps called lineScanner , ie, Scanner lineScanner = new Scanner(line);
  • And I'd parse each token with this Scanner, and inside of an inner try / catch InputMismatchException block . If it fails, the catch should get this, and you can handle it.
  • As noted by Tom, if you're using Java 7, then go with Try with resources . This way your Scanners will close automatically when you're done with them.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM