7-3 类和对象的使用

1.创建一个类Student,具体属性和方法如下:
属性:(全部私有,数据类型自己选择使用)
姓名(name),性别(sex),学号(studentID),年龄(age),专业(major)
方法:
(1)定义一个空参数构造器public Student();
(2)定义一个多参数的构造器,用于为所有属性赋值public Student(String name,String sex,String studentID,int age,String major)
(3)由于所有属性私有的,为所有属性提供getter()和setter()方法;
(4)public String toString()用于返回学生的所有属性信息;
(5)public void printInfo()用于打印学生的信息
2.定义一个测试类Test,在main方法中创建一个Student对象,根据提示输入学生信息保存在对象中,调用printInfo()方法输出学生信息。
3.输出结果参考“输出样例”

输入格式:

请在这里写输入格式。例如:输入在一行中给出2个绝对值不超过1000的整数A和B。

输出格式:

姓名:Tom,性别:23,学号:20221201234,年龄:23,专业:计算机科学

输入样例:

在这里给出一组输入。例如:

 

张三
男
23
计算机科学
2022120

答案: 

import java.util.Scanner;

public class Main{
    public static void main(String args[]){
        String name;
        String sex;
        String studentID;
        int age;
        String major;
        Scanner shuru=new Scanner(System.in);
        name=shuru.next();
        sex=shuru.next();
        age=shuru.nextInt();
        major=shuru.next();
        studentID=shuru.next();
        
        Student s1=new Student(name, sex, studentID, age, major);
        s1.printInfo();
        s1.toString();
    }
}
class Student{
    private String name;
    private String sex;
    private String studentID;
    private int age;
    private String major;
    public Student(){};
    public Student(String name,String sex,String studentID,int age,String major){
        this.name=name;
        this.sex=sex;
        this.studentID=studentID;
        this.age=age;
        this.major=major;
    }
    public void set(){
    }
    public String getname(String name){
        return this.name;
    }
    public String getsex(String sex){
        return this.sex;
    }
    public String studentID(String studentID){
        return this.studentID;
    }
    public int age(int age){
        return this.age;
    }
    public String major(String major){
        return this.major;
    }

    public String toString(){
        return "姓名:"+this.name+", 性别:"+this.sex+", 学号:"+this.studentID+", 年龄:"+this.age+", 专业:"+this.major;}//获取学生所有属性的方法
    public void printInfo(){
        System.out.print("姓名:"+this.name);
        System.out.print(",性别:"+this.sex);
        System.out.print(",学号:"+this.studentID);

        System.out.print(",年龄:"+this.age);
        System.out.print(",专业:"+this.major);

    }
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值