1. 程式人生 > >Java——Person類3

Java——Person類3

Description

在Person類的基礎上,新增一個靜態變數avgAge表示所有Person物件的平均年齡(整數),提供方法getAvgAge能夠讀取該靜態變數。
main函式中,構造三個Person類的物件,讀入他們的資訊,並輸出他們的平均年齡

Input

多個使用者資訊

Output

平均年齡

Sample Input

a male 23
b female 21
c male 22

Sample Output

22

HINT

在建構函式裡對靜態變數avgAge進行更新
import java.util.*;

public class Main{

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in); 

        Person p = new Person();

        for(int i = 0;i<3;i++)

        {

        String name = scan.next();      

        String sex = scan.next();      

        int age = scan.nextInt();

        p = new Person(name,sex,age);

        }

        System.out.println(p.getAvgAge());

   }

}

class Person {

    private String name;

    private String sex;

    private int age;

    static int avgAge = 0;

    public Person()

    {

        name = null;

        sex = null;

        age = 0;

    }

    public Person(String n, String s,int a)

    {

        name = n;

        sex = s;

        age = a;

        avgAge += age;

    }

    public int getAvgAge()

    {

        return avgAge/3;

    }

    public void setName(String n)

    {

        name = n;

    }

    public void setSex(String s)

    {

        sex = s;

    }

    public void setAge(int a)

    {

        age = a;

    }

}