java物件導向作業3

main_OmO發表於2020-09-23

題目3:

設計,並定義一個學員類:Student,要求有以下屬性:

	學員編號(String) 
	姓名(String)
	性別(String)
	身高(double)
	年齡(int)

使用封裝的原則,並提供無參和全參的構造方法。

1 定義MainApp類,幷包含main()方法。

2 在main方法,執行程式,應分別提示使用者輸入學員編號、姓名等資訊。

【提示:鍵盤輸入字串。String s = sc.next();】

例如控制檯顯示:

請輸入學員編號:
xxx
請輸入學員姓名:
xxx

資料接收到程式中,並定義變數儲存;

建立Student物件,通過構造方法將所有資料儲存到Student物件中;

在main方法中獲取並列印物件中的每個屬性值。

參考程式碼:

public class Student {
    private String id;
    private String name;
    private String gender;
    private double height;
    private int age;
    public Student(){}
    public Student(String id, String name, String gender, double height, int age) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.height = height;
        this.age = age;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

import java.util.Scanner;
public class MainApp {
    public static void main(String[] args) {
        System.out.println("請輸入您的編號");
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        System.out.println("請輸入您的姓名");
        Scanner sc1 = new Scanner(System.in);
        String s2 = sc.nextLine();
        System.out.println("請輸入您的性別");
        Scanner sc2 = new Scanner(System.in);
        String s3 = sc.nextLine();
        System.out.println("請輸入您的身高");
        Scanner sc3 = new Scanner(System.in);
        double s4 = sc.nextDouble();
        System.out.println("請輸入您的年齡");
        Scanner sc4 = new Scanner(System.in);
        int s5 = sc.nextInt();
        Student student = new Student(s1,s2,s3,s4,s5);
        System.out.println(student.getId());
        System.out.println(student.getName());
        System.out.println(student.getGender());
        System.out.println(student.getHeight());
        System.out.println(student.getAge());
    }
}

相關文章