捕获输入异常

要求:编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。

考虑到可能输入非数值型数据,所以增加异常处理,捕获异常。

 1 package com.test;
 2 
 3 import java.rmi.MarshalException;
 4 import java.util.InputMismatchException;
 5 import java.util.Scanner;
 6 
 7 public class chengji {
 8 
 9     public static void main(String[] args) {
10         int flag = 1;
11     
12         while (flag == 1) {
13             Scanner in = new Scanner(System.in);
14             int m = -1;
15             try {
16     
17             System.out.print("请输入考试成绩:");
18             m = in.nextInt();
19             
20             }catch(InputMismatchException e) {
21                 System.out.print("应输入整数");
22             }
23             
24             if (90 <=m && m <= 100) {
25                 System.out.println("优");
26             }
27             if (80 <= m && m < 90) {
28                 System.out.println("良");
29             }
30             if (70 <= m && m< 80) {
31                 System.out.println("中");
32             }
33             if (60 <= m && m < 70) {
34                 System.out.println("及格");
35             }
36             if (0 <= m && m <60) {
37                 System.out.println("不及格");
38             }
39             if(m>100||m<0){
40                 System.out.println("输入错误!");
41                 flag=0;
42             }
43         }
44         
45     }
46 }

原文地址:https://www.cnblogs.com/znjy/p/13991581.html