package com.test4;
import java.io.*;/** * @author qingfeng * * 功能:对象数组的使用 * * 养狗场问题:命令行输入狗的名字和体重 * 问题1:计算它们的平均体重 * 问题2:找出最大和最小狗的名字 * 问题3:输入某个狗可以显示其体重 */public class Object { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Dog[] dogs = new Dog[4];//对象数组! Float totalWeight=0f; for(int i=0; i<dogs.length; i++) { dogs[i] = new Dog();//很重要!否则会报空指针错误!(因为数组存的是对象的引用) System.out.println("请输入第"+(i+1)+"个狗的名字:"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String name = br.readLine(); dogs[i].setName(name); System.out.println("请输入第"+(i+1)+"个狗的体重:"); String s_weight = br.readLine(); Float weight= Float.parseFloat(s_weight); dogs[i].setWeight(weight); totalWeight += dogs[i].getWeight(); } System.out.println("平均重量为:"+(totalWeight/dogs.length)); //选择排序思想找出最大重量和最小重量 float maxWeight; 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)+"只狗,重量为"+maxWeight); float minWeight; minWeight = dogs[0].getWeight(); int minIndex = 0; for(int i=1; i<dogs.length; i++) { if(minWeight > dogs[i].getWeight()) { minWeight = dogs[i].getWeight(); minIndex = i; } } System.out.println("最大重量的狗是第"+(minIndex+1)+"只狗,重量为"+minWeight); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String name = br.readLine(); int flag = 0; //判断是否和数组存在的值相等 //易错点:String、对象判断相等用“equals”方法 ;int float double判断相等用“==” for (int i = 0; i < dogs.length; i++) { if (dogs[i].getName().equals(name)) { System.out.println("狗的重量为:" + dogs[i].getWeight()); flag = 1; } } if (flag == 0) { System.out.println("你输入的狗不存在!"); } } }class Dog{ //私有变量 private String name; private float weight; //setter和getter方法 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; }}
/******************************************************************/
/***********************************************************************/