java 中 ArrayList 的 For 循环

For loop for ArrayList in java

所以我在遍历格式如下的 .txt 文件时遇到问题:

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

现在我知道 .txt 文件中有故意的错误,这就是我的 catch (InputMismatchException n) 发挥作用的地方。我应该找出 .txt 文件中的任何不匹配项并将其存储在另一个 .txt 文件中。

我卡住的部分是我似乎无法找出 try/catch 方法之外的循环来在 InputMismatchException 之后成功地继续查看 .txt 文件被发现...

我试过 for 循环,但是设置 int i = 0; 基本上不会启动我的程序,因为 Arraylist ArrEmployee 的大小是 null? (据我了解Java)

这是我的代码(你的 Windows 用户名在哪里):

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

我看到你的主要错误是你的 while 循环在你的行读取 try/catch 块中,所以当你 运行 时没有办法恢复到循环陷入错误。

改为:

  • 是的,您的文件首先获取 try / catch (FileNotFoundException ...) 并将所有其余代码都包含在其中。
  • 然后执行你的 while 循环
  • 然后在你的 while 循环中捕获 InputMismatchException。
  • 我自己,我会使用基于文件的扫描仪,比如命名,fileScanner
  • 我的 while 循环会循环 while (fileScanner.hasNextLine())
  • while 循环内的第一行,我将通过调用 fileScanner.nextLine().
  • 提取 整行
  • 然后我会根据获得的行在 while 循环内创建第二个扫描器,可能称为 lineScanner,即 Scanner lineScanner = new Scanner(line);
  • 我会用这个扫描器解析每个标记,在内部 try / catch InputMismatchException 块中。如果失败,catch应该得到这个,你可以处理它。
  • 正如 Tom 所说,如果您使用的是 Java 7,那么请使用 Try with resources。这样,您的扫描仪将在您完成使用后自动关闭。

在伪代码中

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

您似乎想逐行读取文件,然后尝试使用 try {} catch {} 解析每一行以捕获格式错误。然后每一行都可以写入一个单独的错误文件。