简体   繁体   中英

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). When a variable in the .txt file ISN'T a long or string or double, it's written into another file. I've written the code of this but it doesn't go past the first 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. From the 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.

You should create txtOut once before the loop and close it after the loop. This way it will only be opened once and not started from scratch for every exception caught.

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