/**
*功能:对象数组的使用
*/
package com.test4;
import java.util.Scanner;
public class Shuzu2 {
public static void main(String[] args) {
//定义一个可以存放四只狗的对象数组
Dog dogs[]=new Dog[4];
//给各个够赋初值(不提倡下面的赋值方式)
// dogs[0]=new Dog();
// dogs[0].setName("花花");
// dogs[0].setWeigh(4.5f);
//
Scanner scr=new Scanner(System.in);
for(int i=0;i<4;i++) {
dogs[i]=new Dog();//如果没有这个new的话程序会报错因为内存给数组开辟空间的时候首先默认是空的
//只有new一下才能实现数组的引用
System.out.println("请输入第"+(i+1)+"狗的名字");
//从键盘输入狗名
String name=scr.nextLine();
//将名字赋给狗
dogs[i].setName(name);
System.out.println("请输入第"+(i+1)+"狗的体重:");
String s_weight=scr.nextLine();
float weight=Float.parseFloat(s_weight); //String->float类型转换
//把体重赋给对象
dogs[i].setWeigh(weight);
}
//先计算总体重
float allWeight=0;
for(int i=0;i<4;i++)
{
allWeight+=dogs[i].getWeight();
}
//计算平均体重
float avgWeight=allWeight/dogs.length;
System.out.println("狗的总体重是:"+allWeight+"\n狗的平均体重是:"+avgWeight);
//找出体重最大的狗
//假设第一只狗的体重最大
float maxWeight=dogs[0].getWeight();
int maxIndex=0;//做标记
for(int i=1;i<4;i++)
{
if(maxWeight<dogs[i].getWeight())
{
//做修改
maxWeight=dogs[i].getWeight();
maxIndex=i;
}
}
//输出
System.out.println("体重最大的是第"+(maxIndex+1)+"只狗"+
"\n体重是"+dogs[maxIndex].getWeight());
}
}
//定义一个狗类
class Dog{
private String name;
private float weight;
public float getWeight() {
return weight;
}
public void setWeigh (float weight) {
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}