Java面向对象程序设计——带异常处理的person类

zhuannnn / 2024-02-01 / 原文

带异常处理的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 {
	String name;
	int age;
	public Person(){
		
	}
	public Person(String name){
		this.name = name;
	}
	public Person(String name, int age) throws Exception{
		this(name);
		setAge(age);
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age)throws Exception{
		if(age>1 && age <100)
			this.age = age;
		else 
			throw new Exception();
	}
	@Override
	public String toString() {
		return '('+name+','+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:
			try{
				p=new Person("zhangsan");
			        p.setAge(50);
			}catch(Exception e){
				System.out.println("IllegalArgumentException");
			}

			break;
		case 2:
			try{
				p=new Person("zhangsan",101);
			}catch(Exception e){
				System.out.println("IllegalArgumentException");
			}
			break;
		case 3:		
			try{
                                p=new Person("zhangsan");
				p.setAge(-1);
			}catch(Exception e){
				System.out.println("IllegalArgumentException");
			}
			break;
		default:
			try{
				p=new Person("zhangsan",20);
			}catch(Exception e){
				System.out.println("IllegalArgumentException");
			}
			
		}
		in.close();
		System.out.println(p);
	}
}

记录Java面向对象课程练习题,方便查阅。如有错误,恳请指出。