简体   繁体   English

我如何处理IOExceptions?

[英]How do I handle IOExceptions?

I am a student and this is my second week of Java. 我是学生,这是我第二周的Java。 the assignment is to get data from the keyboard, for a student name, ID, and three test scores. 分配是从键盘获取数据,学生姓名,ID和三个考试分数。 Then display the primary data using JOptionPane. 然后使用JOptionPane显示主数据。 I believe that I have all of that done. 我相信我完成了所有这些。 I've taken the assignment a little further so that I can learn about unit testing as well. 我进一步完成了任务,以便我也可以学习单元测试。

The problem is that the ID and test scores are supposed to be numbers. 问题是ID和测试分数应该是数字。 If a non-numeric value is entered I get IOExceptions. 如果输入非数字值,我会得到IOExceptions。 I think I need to use try/catch but everything I have seen so far is leaving me confused. 我想我需要使用try / catch,但到目前为止我所看到的一切让我感到困惑。 Could someone please break down how the try/catch works so that I can understand it? 有人可以分解一下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(""));

You should not use try-catck block to check number format. 您不应该使用try-catck块来检查数字格式。 It is expensive. 它是昂贵的。 You may use following code portion. 您可以使用以下代码部分。 It could be more usefull. 它可能更有用。

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

The problem is you are using nextInt() method which expects an integer as input. 问题是你正在使用nextInt()方法,它需要一个整数作为输入。 You should either validate user inputs or give the user specific instructions to input valid numbers. 您应该验证用户输入或为用户提供输入有效数字的具体说明。

Using try catch in java: 在java中使用try catch:

Exception is simply execution of instructions in a unintended/unexpected way. 例外是简单地以非预期/意外的方式执行指令。 Java handles exceptions by try,catch clause. Java通过try,catch子句处理异常。 Syntax is as follows. 语法如下。

try{  

//suspected code

}catch(Exception ex){

//resolution

} 

Put your suspected code that might throw an exception inside the try block. 可能引发异常的可疑代码放入try块中。 And inside the catch block, put the code that resolves a problem if something would go wrong while executing the suspected code. 并且在catch块内部, 如果在执行可疑代码时出现问题,请放置解决问题的代码。

You can find a comprehensive explanation here and a summarized version here . 你可以找到一个全面的解释这里和汇总版本在这里

Try this: 试试这个:

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

I recommend you wrap only code that throws the exception, and not wrap tons of lines with code. 我建议你只包装抛出异常的代码,而不是用代码包装大量的行。
At the catch block you should consider what to do if you have IOException. 在catch块,你应该考虑如果你有IOException该怎么做。
You can have only one catch block as suggested by @Quoi, 根据@Quoi的建议,您只能拥有一个捕获块,
But you may consider having different catch blocks per exception 但是你可以考虑每个异常都有不同的catch块
(bare in mind that the order of the catch blocks should be in such a way that subclasses come first). (请记住,catch块的顺序应该是以子类为先的方式)。 For example, at some application I developed, 例如,在我开发的某些应用程序中,
some exceptions were severe, so we stopped handling, and some were not severe, so we continued to the next phase. 一些例外是严重的,所以我们停止处理,有些不严重,所以我们继续下一阶段。
So our catch blocks set a boolean flag whether to continue or not to the next stage. 所以我们的catch块设置一个布尔标志是否继续下一个阶段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM