卡车要装载一批货物,货物由三种商品组成:电视、计算机、洗衣机。卡车需要计算出整批货物的重量。
要求有一个ComputerWeight接口,该接口中有一个方法:
public double computeWeight()
######有三个实现该接口的类:Television、Computer和WashMachine. 这三个类通过实现接口给出自重。这3个类都有属性weight,并通过构造方法初始化,其中Television类的computeWeight()方法,返回weight值;Computer的computeWeight()方法,返回2倍weight值;WashMachine的computeWeight()方法,返回3倍weight值
有一个卡车Truck类,该类用ComputeWeight接口类型的数组作为成员(Truck类面向接口),那么该数组的元素就可以存放Television对象的引用、Computer对象的引用或WashMachine
对象的引用。程序能输出Truck对象所装载的货物的总重量。
接口方法定义:
ComputerWeight接口的方法:
public double computeWeight();
该方法 在不同实现类中实现不同,Television类的computeWeight()方法,返回weight值;Computer的computeWeight()方法,返回2倍weight值;WashMachine的computeWeight()方法,返回3倍weight值。
裁判测试程序样例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ComputerWeight[] goods=new ComputerWeight[650]; //650件货物
double[] a=new double[3];//存储Television,Computer,WashMachine对象weight属性初值
Scanner sc=new Scanner(System.in);
String str1=sc.nextLine();
String[] str_a=str1.split(" ");
for(int i=0;i<3;i++)
a[i]=Double.parseDouble(str_a[i]);
for(int i=0;i<goods.length;i++) { //简单分成三类
if(i%3==0)
goods[i]=new Television(a[0]);
else if(i%3==1)
goods[i]=new Computer(a[1]);
else if(i%3==2)
goods[i]=new WashMachine(a[2]);
}
Truck truck=new Truck(goods);
System.out.printf("货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeights());
goods=new ComputerWeight[68]; //68件货物
for(int i=0;i<goods.length;i++) { //简单分成两类
if(i%2==0)
goods[i]=new Television(a[0]);
else
goods[i]=new WashMachine(a[2]);
}
truck.setGoods(goods);
System.out.printf("货车装载的货物重量:%-8.5f kg\n",truck.getTotalWeights());
}
}
/* 请在这里填写答案 */
//定义 接口ComputerWeight 代码写在下面
//定义类 Television 实现接口ComputerWeight 代码写在下面
//定义类Computer实现接口ComputerWeight 代码写在下面
//定义类WashMachine 实现接口ComputerWeight 代码写在下面
//类Truck ,实现相关成员方法 代码写在下面
输入样例:
3.5 2.67 13.8
输出样例:
货车装载的货物重量:10860.68000 kg
货车装载的货物重量:1526.60000 kg
我的答案
class Truck
{
ComputerWeight goods[];
Truck(ComputerWeight[] goods) {
super();
this.goods = goods;
}
public void setGoods(ComputerWeight[] goods) {
this.goods = goods;
}
public double getTotalWeight()
{
double sum=0;
for(ComputerWeight i:goods)
{
sum += i.computerWeight();
}
return sum;
}
}
interface ComputerWeight
{
double computerWeight();
}
class Television implements ComputerWeight
{
double w;
Television(double w) {
super();
this.w = w;
}
public double computerWeight()
{
return w;
}
}
class Computer implements ComputerWeight
{
double weight;
Computer(double weight)
{
this.weight=weight;
}
public double computerWeight()
{
return 2*weight;
}
}
class WashMachine implements ComputerWeight
{
double weight;
WashMachine(double weight)
{
this.weight=weight;
}
public double computerWeight()
{
return 3*weight;
}
}