Student Class-Constructor (Java)

Define a Student class about students, containing class member variables: String name, String sex, int age , all variables must be private .
###1. Write a constructor with parameters: assign values ​​to name, sex, age .
###2. Override the toString function :

According to the format: class name [name=, sex=, age=] output.
3. Generate setter/getter methods for each attribute. 4. In the
main method, enter 1 line of name age sex and call the parameterized constructor above to create a new object.

Input example:
tom 15 male

Sample output:
Student [name='tom', sex='male', age=15]

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc=new Scanner(System.in);
        String s = sc.nextLine();
        String[] str=s.split(" ");
        Student student=new Student(str[0],str[2],Integer.valueOf(str[1]));
        System.out.println(student);
    }
}
class Student  {
    
    
    private String name;
    private String sex;
    private int age;

    public void setName(String name){
    
    
        this.name=name;
    }

    public void setsex(String sex){
    
    
        this.sex=sex;
    }

    public void setage(int age){
    
    
        this.age=age;
    }

    public String getName() {
    
    
        return name;
    }

    public String getSex() {
    
    
        return sex;
    }

    public int getAge() {
    
    
        return age;
    }

    @Override
    public String toString() {
    
    
        String str="Student [name='"+name+"', sex='"+sex+"', age="+age+"]";
        return str;
    }


    public Student(){
    
    

    }

    public Student(String name, String sex, int age) {
    
    
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
}

Guess you like

Origin blog.csdn.net/weixin_51430516/article/details/115120473