/**
* 对象数组的使用
*/
package com.test5;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test2 {
private static final BufferedReader br = null;
public static void main(String[] args) throws Exception{
//定义一个可以存放四只狗的对象数组
Dog dogs[]=new Dog[4];
//给各个狗赋初值
/* dogs[0]=new Dog();
dogs[0].setName("花花");
dogs[0].setWeigth(4.5f);
*/
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
for(int i=0;i<4;i++)
{
dogs[i]=new Dog();
System.out.println("请输入第"+(i+1)+"狗名");
//从控制台读取狗名
String name=br.readLine();
dogs[i].setName(name);
System.out.println("请输入体重");
String s_weight=br.readLine();
float weight=Float.parseFloat(s_weight);
//将名字赋给对象
dogs[i].setWeight(weight);
}
//计算平均体重
float allWeight=0;
for(int i=0;i<4;i++){
allWeight+=dogs[i].getWeight();
}
float acWeight=allWeight/dogs.length;
System.out.println("总体中="+allWeight+"平均体重"+acWeight);
//找出体重最大的狗
//假设第一只狗体重最大
float maxWeight=dogs[0].getWeight();
int maxIndex=0;
for(int i=1;i<dogs.length;i++){
if(maxWeight<dogs[i].getWeight()){
maxWeight=dogs[i].getWeight();
maxIndex=i;//下标改变
}
}
System.out.println("体重最大的够是第"+(maxIndex+1)+"体重是"+dogs[maxIndex].getWeight());
//根据狗名查找狗的体重
System.out.println("请输入需要查找的狗名:");
String name=br.readLine();
for(int i=0;i<dogs.length;i++){
if(name.equals(dogs[i].getName())){
System.out.println("你要找的狗是:" + dogs[i].getName() + "体重是:" + dogs[i].getWeight());
}
}
}
}
//定义一个狗类
class Dog{
private String name;
private float weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
}