带异常处理的person类
【问题描述】定义一个Person类,属性包含姓名、年龄。方法:无参构造方法、有参构造方法、getter和setter方法、toString方法。其中:setter方法在设置年龄的时候,要求对年龄进行参数的正确性检测,年龄有效范围在1-100之间,否则跑出IllegalArgumentException异常
【输入形式】1-4的整数
【输出形式】当输入1,结果为(zhangsan,50),输入:2,
结果为:
IllegalArgumentException
null
输入3,结果为:
IllegalArgumentException
(zhangsan,0)
import java.util.Scanner;
class Person{
private String name;
private int age;
public Person() {
}
public Person(String name){
this.name=name;
}
public Person(String name, int age) {
this.setName(name);
this.setAge(age);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
if (age >= 0 && age <= 100)
this.age = age;
else
throw new IllegalArgumentException("参数非法");
}
public int getAge() {
return age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "(" + this.name + "," + this.age + ")";
}
}
public class App {
public static void main(String[] args) {
int i;
Scanner in=new Scanner(System.in);
i=in.nextInt();
Person p=null;
switch(i){
case 1:
p=new Person("zhangsan");
p.setAge(50);
break;
case 2:
try{
p=new Person("zhangsan",101);
}catch(Exception e){
System.out.println("IllegalArgumentException");
}
break;
case 3:
p=new Person("zhangsan");
try{
p.setAge(-1);
}catch(Exception e){
System.out.println("IllegalArgumentException");
}
break;
default:
p=new Person("zhangsan",20);
}
in.close();
System.out.println(p);
}
}