面向对象求3辆车的平均值
自己练习
package com.fqs.demo1; import java.util.Scanner; public class CarTest2 { public static void main(String[]args) { //1.定义一个数组arr存放3个车 Car []arr=new Car[3]; //2.从键盘获取数据 Scanner sc=new Scanner(System.in); //3.循环获取值放到数组中 for(int i=0;i<arr.length;i++) { //初始化对象 Car c=new Car(); //3.1提示输入品牌 System.out.println("请输入品牌"); String brand=sc.next(); //3.1.1将品牌传入对象c的品牌中 c.setBrand(brand); //3.2提示输入价格 System.out.println("请输入价格"); Double price=sc.nextDouble(); //3.2.1将价格传给c的价格中 c.setPrice(price); //3.3提示输入颜色 System.out.println("请输入颜色"); String color=sc.next(); //3.3.1将颜色传到c的颜色中 c.setColor(color); //将c 放到数组arr中 arr[i]=c; } //4.输出数组内的值 Double sum=1.00; for(int i=0;i<arr.length;i++) { Car c=arr[i]; System.out.println(c.getBrand()+" "+c.getPrice()+" "+c.getColor()); //5.求3辆车的总和 sum=+c.getPrice(); } //6.平均值 System.out.println("avg:"+sum/3); } }
学习后
package com.fqs.demo1; public class CarTest { public static void main(String[]args) { //1.数组arr存放3个汽车Car arr[]=new Car[3] Car []arr=new Car[3]; //2.直接定义输入的3个车 arr[0]=new Car("BMW",3000.00,"RED"); arr[1]=new Car("老年代步车",30.00,"RED"); arr[2]=new Car("电动车",2.00,"RED"); Double sum=1.00; ////3.循环3次键盘输入品牌\价格\颜色 for(int i=0;i<arr.length;i++) { //4.初始化Car c=new Car(); Car c=arr[i]; sum=sum+c.getPrice(); System.out.println("品牌:"+c.getBrand()+" "+"价格:"+c.getPrice()+" "+"颜色:"+c.getColor()); } System.out.println("sum:"+sum); //5.求平均值 Double avg=1.00; avg=sum/arr.length; System.out.println("avg:"+avg); } }
再次练习
package com.fqs.demo1; public class CarTest { public static void main(String[]args) { //1.定义数组arr Car []arr=new Car[3]; //2.数组[0],[1],[2]存值 打破常规右边 new Car(品牌,价格,颜色) arr[0]=new Car("bmw",1000.00,"red"); arr[1]=new Car("bmw",1000.00,"red"); arr[2]=new Car("bmw",1000.00,"red"); //3.求和 Double sum=0.00; for(int i=0;i<arr.length;i++) { sum=sum+arr[i].getPrice(); } //4.求平均值 Double avg=0.00; avg=sum/arr.length; System.out.println("avg:"+avg); } }