首页 > 代码库 > 习题:用数组的方法从控制端输入狗名和狗的体重,求总体中和平均值

习题:用数组的方法从控制端输入狗名和狗的体重,求总体中和平均值

public class Test1 {

     

     

     public static void main (String args[]) throws Exception

     {

           Dog dogs[] = new Dog[4];

           

           

           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( "请输入狗民" );

                

                String name= br.readLine(); //抛出异常

                 //将名字赋给对象

                dogs[i].setName(name);

                System. out.println( "请输入狗的体重" );

                String s_weight=br.readLine();

                 int weight = Integer. parseInt(s_weight);

                 //将名字赋给对象

                dogs[i].setWeight(weight);

                

                

           }

           

            //计算平均体重

            //zongtizhongs

            int allWeight=0;

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

           {

                allWeight+=dogs[i].getWeight();

           }

            int avgWeight=allWeight/dogs. length;

           System. out.println( "总体中"+allWeight+"平均体重" +avgWeight);

    }

}



class Dog

{

     private String name;

     private int weight;

     public String getName() {

            return name;

     }

     public void setName(String name) {

            this. name = name;

     }

     public int getWeight() {

            return weight;

     }

     public void setWeight( int weight) {

            this. weight = weight;

     }

     

     

}


本文出自 “小小geek一枚” 博客,请务必保留此出处http://howardhuang.blog.51cto.com/9812975/1606692

习题:用数组的方法从控制端输入狗名和狗的体重,求总体中和平均值