如何处理IOExceptions?

4

我是一名学生,这是我学习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个回答

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

不应该使用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);

这对我有用。为了确保我理解这一点,我将scan.next分配给一个字符串。然后检查以验证字符串的内容是否与数字0-9匹配。当它们匹配时,它会将它们转换为整数并退出循环。 - user1793408

1
问题在于您正在使用nextInt()方法,该方法期望输入一个整数。您应该验证用户输入或向用户提供输入有效数字的具体说明。
在Java中使用try catch:
异常只是以一种意外/意外的方式执行指令。Java通过try、catch子句处理异常。语法如下。
try{  

//suspected code

}catch(Exception ex){

//resolution

} 

将您怀疑可能会引发异常的代码放入try块中。在catch块内,编写解决问题的代码以if当执行该怀疑代码时出现问题时。
您可以在此处找到全面的解释here和概述here

感谢提供这个详尽的解释链接!我会仔细阅读。 - user1793408

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

谢谢,我尝试了这个方法,它处理了异常,但没有循环。然后我尝试了@MMC18的建议,那个方法起作用了。 - user1793408
我想我知道为什么这对我不起作用。我更改了while循环,因为intStudentID初始化为0。我犯的错误是使用“and”子句而不是“or”。 - user1793408

0

我建议您只包装抛出异常的代码,而不是将大量代码都包装起来。
在catch块中,如果有IOException,您应该考虑要做什么。
您可以像@Quoi建议的那样只有一个catch块,
但是您也可以考虑每个异常设置不同的catch块
(请注意,catch块的顺序应该是这样的,子类首先出现)。 例如,在我开发的某个应用程序中,
有些异常非常严重,所以我们停止了处理,而有些异常不是很严重,所以我们继续进行下一阶段。
因此,我们的catch块设置了一个布尔标志,指示是否继续进行到下一个阶段。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接