简体   繁体   English

在Java中的while循环内尝试捕获

[英]Try-Catch inside a while loop in Java

So basically my code is trying to read off a .txt file and then create objects with those variables (long,string,string,double,double). 因此,基本上我的代码试图读取.txt文件,然后使用这些变量(长,字符串,字符串,双精度,双精度)创建对象。 When a variable in the .txt file ISN'T a long or string or double, it's written into another file. 当.txt文件中的变量不是长整数,字符串或双精度型时,它将被写入另一个文件中。 I've written the code of this but it doesn't go past the first catch (InputMismatchException n) . 我已经编写了此代码,但没有超出第一个catch (InputMismatchException n) What is wrong with my code? 我的代码有什么问题?

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

The path files are OK. 路径文件正常。 I've shortened it for easier understanding. 我已将其缩短以方便理解。

The constructor you're using for PrintWriter actually overwrites the file if it already exists. 如果文件已经存在,则用于PrintWriter的构造函数实际上会覆盖该文件。 From the documentation : 文档中

fileName - The name of the file to use as the destination of this writer. fileName用作此编写器目标的文件名。 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. 输出将被写入文件并被缓冲。

You should create txtOut once before the loop and close it after the loop. 您应该在循环之前创建一次txtOut ,并在循环之后关闭它。 This way it will only be opened once and not started from scratch for every exception caught. 这样,它只会被打开一次,不会为捕获到的每个异常从头开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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