gpt4 book ai didi

java - Java 中 while 循环内的 Try-Catch

转载 作者:行者123 更新时间:2023-12-01 11:46:06 25 4
gpt4 key购买 nike

所以基本上我的代码是尝试读取 .txt 文件,然后使用这些变量(long、string、string、double、double)创建对象。当 .txt 文件中的变量不是长整型、字符串或 double 型时,它会被写入另一个文件中。我已经编写了该代码,但它没有超出第一个 catch (InputMismatchException n)。我的代码有什么问题吗?

int i = 0;
ArrayList<Employee> ArrEmployee = new ArrayList<Employee>(); // array for employee objects

try {
Scanner txtIn = new Scanner(new File("payroll.txt"));


while (txtIn.hasNext()) { // looping through the payroll.txt file and creating Employee objects from its data
try {
long EmployeeNumber = txtIn.nextLong();
String EmployeeName = txtIn.next();
String LastName = txtIn.next();
double HoursWorked = txtIn.nextDouble();
double HourlyWage = txtIn.nextDouble();
if (HourlyWage > 10.35){
throw new InputMismatchException(); // throws exception if the hourly wage is less than 10.35$
}
else
ArrEmployee.add(new Employee(EmployeeNumber,EmployeeName,LastName,HoursWorked,HourlyWage)); // creates Employee objects according to the input payroll.txt
i++;
} catch (InputMismatchException n) { // catching long,strings and doubles in the payroll.txt that aren't valid
PrintWriter txtOut = new PrintWriter("payrollError.txt");
txtOut.println(Employee.EmployeeNumber + " " + Employee.EmployeeName + " " + Employee.LastName + " " + Employee.HoursWorked + " " + Employee.HourlyWage);
txtOut.close();
}
}
} catch (FileNotFoundException e) {
System.out.println("File payroll.txt was not found.");
}

路径文件没问题。为了更容易理解,我缩短了它。

最佳答案

您用于 PrintWriter 的构造函数实际上会覆盖该文件(如果该文件已存在)。来自 documentation :

fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

您应该在循环之前创建txtOut一次,并在循环之后关闭它。这样它只会被打开一次,并且不会为每个捕获的异常从头开始。

关于java - Java 中 while 循环内的 Try-Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29113194/

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