簡體   English   中英

我如何處理IOExceptions?

[英]How do I handle IOExceptions?

我是學生,這是我第二周的Java。 分配是從鍵盤獲取數據,學生姓名,ID和三個考試分數。 然后使用JOptionPane顯示主數據。 我相信我完成了所有這些。 我進一步完成了任務,以便我也可以學習單元測試。

問題是ID和測試分數應該是數字。 如果輸入非數字值,我會得到IOExceptions。 我想我需要使用try / catch,但到目前為止我所看到的一切讓我感到困惑。 有人可以分解一下try / catch的工作方式,以便我能理解它嗎?

//Import packages
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**
 *
 * @author Kevin Young
 */

public class StudentTestAverage {

    //A reusable method to calculate the average of 3 test scores
    public static double calcAve(double num1, double num2, double num3){
        final double divThree = 3;
        return (num1 + num2 + num3 / divThree);
    }

    //A method to turn a doule into an integer
    public static int trunAve(double num1){
        return (int) num1;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        //Input variables
        String strStudentName = "";
        int intStudentID = 0;
        double dblScore1 = 0.0;
        double dblScore2 = 0.0;
        double dblScore3 = 0.0;
        String strNumber = ""; //Receives a string to be converted to a number

        //Processing variables
        double dblAverage = 0.0;
        int intAverage = 0;

        /**
         * Create objects that read keyboard data from a buffer
         */

        //Create the reader and Buffer the input stream to form a string
        BufferedReader brObject = 
                new BufferedReader(new InputStreamReader(System.in));

        //Get the student's name
        do{
            System.out.print("Please enter the student's name?");
            strStudentName = brObject.readLine();
        }while(strStudentName.equals(""));

        //Use the scanner to get the student ID
        //this method converts the string to an Integer
        Scanner scan = new Scanner(System.in);

        do{
            System.out.print("Please enter the student's ID?");
            intStudentID = scan.nextInt();
       }while(Double.isNaN(intStudentID));
       /*
        * The above do while loop with the Scanner isn't working as
        * expected. When non-numeric text is entered it throws an 
        * exception. Has the same issue when trying to use parseInt().
        * Need to know how to handle exceptions.
        */


       /**
        * Us JOption to get string data and convert it to a double
        */
        do{
            strNumber = JOptionPane.showInputDialog("Please enter the first test score?");
            dblScore1 = Double.parseDouble(strNumber);
        }while(Double.isNaN(dblScore1));

        do{
            strNumber = JOptionPane.showInputDialog("Please enter the second test score?");
            dblScore2 = Double.parseDouble(strNumber);
        }while(Double.isNaN(dblScore2));

        do{
            strNumber = JOptionPane.showInputDialog("Please enter the third test score?");
            dblScore3 = Double.parseDouble(strNumber);
        }while(Double.isNaN(dblScore3));

        //Calculate the average score
        dblAverage = calcAve(dblScore1, dblScore2, dblScore3);

        //Truncate dblAverage making it an integer
        intAverage = trunAve(dblAverage);


        /**
         * Display data using the JOptionPane
         */
        JOptionPane.showMessageDialog(
                null, "Student " + strStudentName + " ID " + 
                Integer.toString(intStudentID) + " scored " +
                Double.toString(dblScore1) + ", " + 
                Double.toString(dblScore2) + ", and " +
                Double.toString(dblScore3) + ".\n For an average of " +
                Double.toString(dblAverage));

        //Output the truncated average
        System.out.println(Integer.toString(intAverage));
    }
}
try{
  // code that may throw Exception
}catch(Exception ex){
 // catched the exception
}finally{
 // always execute
}

do{
    try{
      System.out.print("Please enter the student's name?");
      strStudentName = brObject.readLine();
    }catch(IOException ex){
       ...
    }
}while(strStudentName.equals(""));

您不應該使用try-catck塊來檢查數字格式。 它是昂貴的。 您可以使用以下代碼部分。 它可能更有用。

    String id;
    do{
        System.out.print("Please enter the student's ID?");            
        id = scan.next();
        if(id.matches("^-?[0-9]+(\\.[0-9]+)?$")){
            intStudentID=Integer.valueOf(id);
            break;
        }else{
            continue;
        }

   }while(true);

問題是你正在使用nextInt()方法,它需要一個整數作為輸入。 您應該驗證用戶輸入或為用戶提供輸入有效數字的具體說明。

在java中使用try catch:

例外是簡單地以非預期/意外的方式執行指令。 Java通過try,catch子句處理異常。 語法如下。

try{  

//suspected code

}catch(Exception ex){

//resolution

} 

可能引發異常的可疑代碼放入try塊中。 並且在catch塊內部, 如果在執行可疑代碼時出現問題,請放置解決問題的代碼。

你可以找到一個全面的解釋這里和匯總版本在這里

試試這個:

 do{
     try{
        System.out.print("Please enter the student's ID?");
        intStudentID = scan.nextInt();
     }catch(IOException e){
         continue; // starts the loop again
     }
 }while(Double.isNaN(intStudentID));

我建議你只包裝拋出異常的代碼,而不是用代碼包裝大量的行。
在catch塊,你應該考慮如果你有IOException該怎么做。
根據@Quoi的建議,您只能擁有一個捕獲塊,
但是你可以考慮每個異常都有不同的catch塊
(請記住,catch塊的順序應該是以子類為先的方式)。 例如,在我開發的某些應用程序中,
一些例外是嚴重的,所以我們停止處理,有些不嚴重,所以我們繼續下一階段。
所以我們的catch塊設置一個布爾標志是否繼續下一個階段。

暫無
暫無

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

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