面向对象程序设计——第三章对象和封装,课后作业。

1.编写一个类,代表学员,具有属性:姓名和年龄,其中年龄不能小于16岁,否则输出错误信息。

import java.util.Scanner;

public class Student1 {
	
	private String name; //姓名
	
	private int age; //年龄
	/**
	 * 判断年龄的方法
	 */
	public void setAge() {
		
		if(age>=16) {
			
			System.out.println("自我介绍:\n我的名字叫:"+this.name+",今年:"+this.age+"岁");
			
		}else {
			
			System.out.println("年龄不够!");
		}
	}
	/**
	 * 从控制台输入学员信息并显示
	 * @param args
	 */
	public static void main(String[] args) {
		
		Student1 Stu = new Student1();
		
		Scanner input = new Scanner(System.in);
		
		System.out.print("请输入姓名:");
		
		Stu.name = input.next();
		
		System.out.print("请输入年龄:");
		
		Stu.age = input.nextInt();
		
		Stu.setAge();
	}
}

2.编写一个类,代表学员,具有属性:姓名和年龄,性别和专业。

具有方法:自我介绍,负责输出该学员的信息。

public class Student2 {

	String name = "翠花"; //姓名
	
	int age = 18; //年龄
	
	String major; //专业
	
	String sex; //性别
	/**
	 * 输出学员信息
	 */
	public void setAge() {
		
		System.out.println("自我介绍:\n我的名字叫:"+this.name+",今年:"+this.age+"岁"
				+",性别:"+this.sex+",专业:"+this.major);
	}
	/**
	 * 无参方法
	 */
	public Student2() {
		
		this.name = "王五";
		
		this.age = 21;
		
		this.major = "java";
		
		this.sex = "男";
	}
	/**
	 * 两个参数的构造方法
	 * @param sex
	 * @param major
	 */
	public Student2(String sex,String major) {
		this.sex = "女";
		
		this.major = "Java";
	}
	/**
	 * 4个参数的构造方法
	 * @param name
	 * @param age
	 * @param major
	 * @param sex
	 */
	public Student2(String name,int age,String major,String sex) {
		this.name = "张三";
		
		this.age = 20;
		
		this.major = "java";
		
		this.sex = "男";
	}
	/**
	 * 测试构造方法
	 * @param args
	 */
	public static void main(String[] args) {
		Student2 Stu = new Student2();
		
		Stu = new Student2();
		
		Stu.setAge();
		
		Stu = new Student2("女","Java");
		
		Stu.setAge();
		
		Stu = new Student2("张三",20,"java","男");
		
		Stu.setAge();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41882685/article/details/80062665