题目要求:对年龄赋值进行判断,不在1-100抛出异常并处理

 1 package demo2;
 2 
 3 /**
 4  * 人类,对年龄赋值进行判断,不在1-100抛出异常并处理
 5  * @author 
 6  *
 7  */
 8 public class Person {
 9     private int age;
10 
11     public int getAge() {
12         return age;
13     }
14     
15     //异常声明
16     public void setAge(int age) throws Exception {
17         this.age = age;
18         if(age<0 || age>100) {
19             throw new Exception("输入的年龄不在1-100之间!");  //异常抛出
20         }
21         
22     }
23     public void showInfo() {
24         System.out.println("您的年龄是:"+age+"岁");
25     }
26 }
 1 package demo2;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test {
 6     public static void main(String[] args) {
 7         Scanner input=new Scanner(System.in);
 8         Person person=new Person();
 9         try {
10             System.out.print("请输入年龄:");
11             int age=input.nextInt();
12             person.setAge(age);
13             person.showInfo();
14         }catch(Exception e) {
15             System.err.println(e.getMessage());
16         }
17         
18         
19     }
20 }

 

posted on 2018-12-04 21:09  从零开始-白  阅读(127)  评论(0编辑  收藏  举报