【实验要求】 货车要装载一批货物,货物由三种商品组成:电视、计算机和洗衣机。卡车需要计算出整批货物的重量。
【实验步骤】UML
过程
在这里插入代码片
public interface ComputerWeight {
public abstract double computerWeight();
}
public class Truck {
ComputerWeight [] goods;
double totalWeight=0;
public Truck(ComputerWeight[] cw) {
this.goods = cw;
}
public void setGoods(ComputerWeight [] goods){
this.goods = goods;
}
public double getTotalWeight(){
for (int i= 0;i<goods.length;i++){
totalWeight+=goods[i].computerWeight();
}
return totalWeight;
}
}
public class Television implements ComputerWeight{
/**
* tv
* @return
*/
@Override
public double computerWeight() {
return 2;
}
}
* @Version 1.0
*/
public class WashMachine implements ComputerWeight{
@Override
public double computerWeight() {
return 5;
}
}
* * @Date 2023/10/1 22:23
* @Version 1.0
*/
public class Computer implements ComputerWeight{
@Override
public double computerWeight() {
return 3;
}
}
public class TruckMain {
public static void main(String[] args) {
// one
ComputerWeight[] goods = new ComputerWeight[650];
// another
ComputerWeight[] goods2 = new ComputerWeight[68];
// truck
Truck truck1 = new Truck(goods);
// truck2
Truck truck2 = new Truck(goods2);
//one
for (int i = 0; i < goods.length; i++) {
if (0 == i % 3) {
goods[i] = new Television();
} else if (1 == i % 3) {
goods[i] = new Computer();
} else if (2 == i % 3) {
goods[i] = new WashMachine();
}
}
// two 2
for (int j = 0; j < goods2.length; j++) {
if (0 == j % 2) {
goods2[j] = new Television();
} else {
goods2[j] = new WashMachine();
}
}
truck1.setGoods(goods);
truck2.setGoods(goods2);
// 1
System.out.println("第一辆货车的装载量:"+truck1.getTotalWeight()+"kg");
// 2
System.out.println("第er辆货车的装载量:"+truck2.getTotalWeight()+"kg");
}
}