Java基礎知識——對象數組

對象數組Object[]。對象數組也是一種引用傳遞,放對象的數組。
1、設計一個學生類、創建一個學生對象數組,保存十個學生對象

2、設計Test類、設計兩個成員方法用來統計學生對象數組中男女生人數以及班級的平均年齡。

學生類。

class Student()
{
	String name;
	int age;
	char  gender;
	Student()
	{
		System.out.println("創建了一個學生對象");
	}
   Student(String name,int age,char gender)
	{
        this.name=name;
		this.age=age;
		this.gender=gender;
    }
	public void introduce()
	{
       System.out.println("姓名:"+this.name+" ,性別"+this.gender+" ,年齡:"+this.age);
	}

}
在同包中創建Test類,統計學生對象數組中男女生人數以及班級的平均年齡。

getGenderNumber(Student[] std,char gender)、averageAge(Student[] std)聲明爲爲靜態方法,可以用類名,直接調用。

for(Student s:std),加強型for循環,適用於不知道循環次數的循環。

Student[] std爲對象數組。

class Test()
{
 public static int getGenderNumber(Student[] std,char gender)
	{
	 int male_number=0;
	 int female_number=0;
	 for(Student s:std)
		{
		 if(s.gender=='M'||s.gender=='m')
			{
			 male_number++;
		 }
		 else if(s.gender=='F'||s.gender=='f')
			{
			 female_number++;
		 }
	 }
	 if(gender=='m'||gender=='M')
		{
	       return male_number;
		 }
		 else
		{
			 return female_number;
		 }
 }

 public static int averageAge(Student[] std)
	{
	   int sum=0;
	   for(Student s:std)
		{
		   sum+=s.age;
	   }
	   return sum/stu.length;
 }
  public static void main(String[] args)
	{
	  Student[] std={
	    new Student("張三","20","M"),
		new Student("李四","21","F"),
		new Student("王五","15","M"),
		new Student("趙六","22","M"),
		new Student("孫七","20","F")
	  };
	//增強型for循環,foreach。實用於數組,集合
	for(Student s:std)
		{
		s.introduce();
		System.out.println("----------------");
		System.out.println("男生人數:"+Test.getGenderNumber(std,'m'));
        System.out.println("女生人數:"+Test.getGenderNumber(std,'f'));	
        System.out.println("平均年齡:"+Test.averageAge(std));	

	}
  }
}
System.out.println("男生人數:"+Test.getGenderNumber(std,'m'));
        System.out.println("女生人數:"+Test.getGenderNumber(std,'f'));
        System.out.println("平均年齡:"+Test.averageAge(std));

分別打印男女生人數和平均年齡。



發佈了32 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章