簡體   English   中英

在Java中的while循環內嘗試捕獲

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

因此,基本上我的代碼試圖讀取.txt文件,然后使用這些變量(長,字符串,字符串,雙精度,雙精度)創建對象。 當.txt文件中的變量不是長整數,字符串或雙精度型時,它將被寫入另一個文件中。 我已經編寫了此代碼,但沒有超出第一個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的構造函數實際上會覆蓋該文件。 文檔中

fileName用作此編寫器目標的文件名。 如果文件存在,它將被截斷為零 ; 否則,將創建一個新文件。 輸出將被寫入文件並被緩沖。

您應該在循環之前創建一次txtOut ,並在循環之后關閉它。 這樣,它只會被打開一次,不會為捕獲到的每個異常從頭開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM