gpt4 book ai didi

java - java中ArrayList的for循环

转载 作者:行者123 更新时间:2023-11-29 05:09:36 25 4
gpt4 key购买 nike

所以我无法遍历格式如下的 .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");
}
}
}
}

最佳答案

在我看来,您的主要错误是您的行读取 try/catch block 中有 while 循环,因此当您遇到错误时无法恢复回循环。

相反:

  • 是的,您的文件首先获取 try/catch (FileNotFoundException ...) 并将所有其余代码包含在其中。
  • 然后执行你的 while 循环
  • 然后在您的 while 循环中捕获 InputMismatchException。
  • 我自己,我会使用一个基于文件的扫描器,比如命名为 fileScanner
  • 我的 while 循环将循环 while (fileScanner.hasNextLine())
  • while 循环内的第一行,我将通过调用 fileScanner.nextLine() 提取整行
  • 然后我会根据获得的行在 while 循环内创建第二个扫描器,可能称为 lineScanner,即 Scanner lineScanner = new Scanner(line);
  • 我会用这个扫描器解析每个标记,在内部 try/catch InputMismatchException block 中。如果失败,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

关于java - java中ArrayList的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com