我如何处理IOExceptions?

时间:2012-11-02 06:40:57

标签: java

我是学生,这是我的第二周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));
    }
}

5 个答案:

答案 0 :(得分:2)

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(""));

答案 1 :(得分:1)

您不应该使用try-catch块来检查数字格式。它是昂贵的。您可以使用以下代码部分。它可能更有用。

    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);

答案 2 :(得分:1)

问题是你正在使用nextInt()方法,它需要一个整数作为输入。您应验证用户输入或为用户提供输入有效数字的具体说明。

在java中使用try catch:

异常只是以非预期/意外的方式执行指令。 Java通过try,catch子句处理异常。语法如下。

try{  

//suspected code

}catch(Exception ex){

//resolution

} 

可能的可疑代码放入 try 块中。在 catch 块中,如果在执行可疑代码时出现问题,请输入解决问题的代码。

您可以找到全面的解释here和摘要版本here

答案 3 :(得分:0)

试试这个:

 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));

答案 4 :(得分:0)

我建议你只包装抛出异常的代码,而不是用代码包装大量的行。
在catch块,你应该考虑如果你有IOException该怎么做。
根据@Quoi,
建议你只能有一个捕获区块 但是你可能会考虑每个异常都有不同的catch块(请记住,catch块的顺序应该是以子类为先的方式)。 例如,在我开发的某些应用程序中,有些例外是严重的,所以我们停止处理,有些并不严重,所以我们继续下一阶段。
所以我们的catch块设置一个布尔标志是否继续下一个阶段。