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

5 回答 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(""));
于 2012-11-02T06:45:58.403 回答
1

您不应该使用 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);
于 2012-11-02T07:01:10.593 回答
1

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

在 java 中使用 try catch:

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

try{  

//suspected code

}catch(Exception ex){

//resolution

} 

可能引发异常的可疑代码放入try块中。如果在执行可疑代码时出现问题,则在catch块中放置解决问题的代码。

您可以在此处找到全面的解释,并此处找到摘要版本。

于 2012-11-02T07:03:05.413 回答
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));
于 2012-11-02T06:47:13.053 回答
0

我建议您只包装引发异常的代码,而不是用代码包装大量行。
在 catch 块中,您应该考虑如果遇到 IOException 该怎么办。
正如@Quoi 所建议的那样,您只能有一个 catch 块,
但是您可以考虑为每个异常设置不同的 catch 块
(请记住,catch 块的顺序应该是子类排在第一位的方式)。比如我开发的某个应用,
有的异常很严重,所以我们停止处理,有的不严重,所以我们继续下一个阶段。
所以我们的 catch 块设置了一个布尔标志是否继续到下一个阶段。

于 2012-11-02T06:49:56.310 回答