某大型家电企业拥有一批送货卡车,运送电视机、洗衣机、空调等家电。编程计算每个卡车所装载货物的总重量。要求有一个Appliance(家电)接口和有三个实现类TV、WashMachine和AirConditioner,这些类能够提供自重。有一个Truck类,包含了该货车上的所有家电,用一个集合(数组或集合类)表示。
Main函数中程序能够输出Truck类所装载货物的总重量。
输入格式:
家电数量
家电种类编号 家电重量
注意:各个家电的编号为:TV:1 WashMachine:2 AirConditioner:3
输出格式:
总重量
输入样例:
在这里给出一组输入。例如:
5
1 20
2 30
3 25
3 30
2 40
输出样例:
在这里给出相应的输出。例如:
145
答案:
import java.util.Scanner;
interface Appliance{
}
class TV implements Appliance{
int id;
int weight;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight=weight;
}
TV(int id,int weight){
this.id=id;
this.weight=weight;
}
}
class WashMachine implements Appliance{
int id;
int weight;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight=weight;
}
WashMachine(int id,int weight){
this.id=id;
this.weight=weight;
}
}
class AirConditioner implements Appliance{
int id;
int weight;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public int getWeight(){
return weight;
}
public void setWeight(int weight){
this.weight=weight;
}
AirConditioner(int id,int weight){
this.id=id;
this.weight=weight;
}
}
class Truck{
int sum;
Truck(int sum){
this.sum=sum;
}
public int show(){
return sum;
}
}
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int sum=0;
for(int i=0;i<n;i++){
int h=sc.nextInt();
if(h==1) {
int weight=sc.nextInt();
sum+=weight;
TV tv=new TV(1,weight);
}
if(h==2) {
int weight=sc.nextInt();
sum+=weight;
WashMachine w=new WashMachine(1,weight);
}
if(h==3) {
int weight=sc.nextInt();
sum+=weight;
AirConditioner a=new AirConditioner(1,weight);
}
}
Truck b=new Truck(sum);
System.out.println(b.show());
}
}