首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何处理IOExceptions?

问如何处理IOExceptions?
EN

Stack Overflow用户
提问于 2012-11-02 14:40:57
回答 4查看 161关注 0票数 4

我是一名学生,这是我学习Java的第二周。任务是从键盘上获取数据,包括学生姓名、ID和三个考试成绩。然后使用JOptionPane显示主要数据。我相信我已经完成了所有的工作。我把任务做得更深入了一点,这样我也可以学习单元测试了。

问题是ID和考试分数应该是数字。如果输入了一个非数字值,我将得到IOExceptions。我认为我需要使用try/catch,但是到目前为止我所看到的一切都让我感到困惑。有人能分析一下try/catch是如何工作的吗?这样我就能理解它了。

代码语言:javascript
复制
//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));
    }
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-11-02 15:01:11

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

代码语言:javascript
复制
    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);
票数 1
EN

Stack Overflow用户

发布于 2012-11-02 14:45:58

代码语言:javascript
复制
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(""));
票数 2
EN

Stack Overflow用户

发布于 2012-11-02 15:03:05

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

在java中使用try :

异常只是以一种意想不到的方式执行指令。Java通过try、catch子句处理异常。语法如下。

代码语言:javascript
复制
try{  

//suspected code

}catch(Exception ex){

//resolution

} 

将可能抛出异常的可疑代码放入try块中。在catch块中,放置代码,用于在执行可疑代码时出错时解决问题。

你可以找到一个全面的解释here和一个总结版本的here。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13190541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档