Calculate the average score

The average score is calculated based on the total number of user input and the total score. Required procedures to handle the case when the total number or the total score is not a number.

When using multiple catch statements, Java virtual machine to actual exception object thrown in turn declared and each catch block matches the type of exception, the catch block if the exception object is an instance of a type of exception or a subclass of implementation while skipping other catch block. code show as below:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Test03 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.println("请输入班级总人数:");
            int count = input.nextInt();
            System.out.println("请输入总成绩:");
            int score = input.nextInt();
            int avg = score / count; // 获取平均分
            System.out.println("本次考试的平均分为:" + avg);
        } catch (InputMismatchException e1) {
            System.out.println("输入数值有误!");
        } catch (ArithmeticException e2) {
            System.out.println("输入的总人数不能为0!");
        } catch (Exception e3) {
            e3.printStackTrace();
            System.out.println("发生错误!" + e3.getMessage());
        }
    }
}

As the code above, () method using multiple main catch statement to catch exceptions may occur in a variety of, including abnormal InputMismatchException, an ArithmeticException abnormalities and other types of anomalies.

When the user inputs the total number or the total score is not numeric type, the program will throw InputMismatchException exception, thereby executing the code line 15, the output results are as follows:

请输入班级总人数:
50
请输入总成绩:
1250v
输入数值有误!
请输入班级总人数:
50v
输入数值有误!

When the total number of the input is zero, the average score will be calculated dividend is zero, at this time will ArithmeticException exception is thrown, so as to perform the code line 17, the output results are as follows:

请输入班级总人数:
0
请输入总成绩:
100
输入的总人数不能为0!

When the input is below the total number and total score are output at the normal value type:

请输入班级总人数:
5
请输入总成绩:
500
本次考试的平均分为:100
Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104736785