Object-Oriented Chapter 3 After-School Exercises

1. Write a class Student1, representing students, the requirements are as follows:

Has attributes: name and age, where the age cannot be less than 16 years old, otherwise an error message is output

With method: self-introduction, responsible for outputting the student's name and age

package com.sjlx.duan;

import java.util.Scanner;

public class Student1 {
	String name="";//姓名
	int age=0;//age
	public void staAge() {
		if (age>16) {//Determine whether the age is over 16 years old
			System.out.println("Introduce myself:\nMy name is:"+name+"\nMy age is:"+age);
		}else {System.out.println("age does not match");}
	}
	public static void main(String[] args) {
		Student1 stu = new Student1();
		Scanner input = new Scanner(System.in);
		System.out.print("Please enter your name:");
		stu.name=input.next();
		System.out.print("Please enter age:");
		stu.age=input.nextInt();
		stu.staAge();//Call the staAge method to output the result
	}
}

2. Write a class Student2, representing students, the requirements are as follows

Has attributes: name, age, gender and profession

With method: self-introduction, responsible for outputting the trainee's name, age, gender and major

There are two constructors with parameters: in the first constructor, the gender of the student is set to male, the major is java, and the values ​​of the remaining attributes are given by parameters. In the second constructor, the values ​​of all attributes are set. are given by parameters

package com.sjlx.duan;

import java.util.Scanner;

public class Student2 {
	String name;//Name
	int avg;//age
	String sex;//Sex
	String profession;//professional
	public void introduce () {//The method of outputting self-introduction
		System.out.println("Self introduction:\n"+"My name is:"+name+"\nMy age is:"+avg+
				"\nMy gender is:"+sex+"\nMy major is:"+profession);
	}
	
	public Student2(String name,int avg) {
		this.sex="男";
		this.profession="JAVA";
		this.name=name;
		this.avg=avg;
	}
	public Student2(String name,int avg,String sex,String profession) {
		this.name=name;
		this.avg=avg;
		this.sex=sex;
		this.profession=profession;
	}
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Please enter your name:");
		String name = input.next();
		System.out.print("Please enter age:");
		int avg = input.nextInt();
		System.out.print("Please enter gender:");
		String sex = input.next();
		System.out.print("Please enter professional:");
		String profession = input.next();
		//create method and pass parameters
		Student2 stu =new Student2(name, avg);
		Student2 stu2 = new Student2(name, avg, sex, profession);
		// call method to output information
		stu.introduce();
		stu2.introduce();
		
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325911195&siteId=291194637