家電類(介面)
阿新 • • 發佈:2018-12-20
140 - 家電類
Time Limit: 1000 Memory Limit: 65535 Submit: 401 Solved: 294
Description
某大型家電企業擁有一批送貨卡車,運送電視機、洗衣機、空調等家電。程式設計計算每個卡車所裝載貨物的總重量。要求有一個Appliance(家電)介面和有三個實現類TV、WashMachine和AirConditioner,這些類能夠提供自重。有一個Truck類,包含了該貨車上的所有家電,用一個集合(陣列或集合類)表示。
Main函式中程式能夠輸出Truck類所裝載貨物的總重量。
Input
家電數量 家電種類編號 家電重量 注意:各個家電的編號為:TV:1 WashMachine:2 AirConditioner:3
Output
總重量
Sample Input
5
1 20
2 30
3 25
3 30
2 40
Sample Output
145
HINT
Pre Append Code
Post Append Code
import java.util.Scanner; interface Appliance //家電介面 { public int getWeight();//定義方法,getWeight() } abstract class elec implements Appliance{ public abstract int getWeight(); } class TV extends elec implements Appliance{ //使用介面(實現介面的類:要實現介面中定義的所有方法) private int weight; TV(int weight){ this.weight = weight; } public int getWeight(){ return weight; } } class WashMachine extends elec implements Appliance{ private int weight; WashMachine(int weight){ this.weight = weight; } public int getWeight(){ return weight; } } class AirConditioner extends elec implements Appliance{ private int weight; AirConditioner(int weight){ this.weight = weight; } public int getWeight(){ return weight; } } class Truck{ int weight = 0; int n; elec[] s; public void getCount(){ Scanner scan = new Scanner(System.in); n = scan.nextInt();//獲取家電數目 s = new elec[n];//申請elec集合類 for(int i = 0;i < n;i ++)//for迴圈輸入家電資訊 { int type = scan.nextInt(); int w = scan.nextInt(); if(type == 1) s[i] = new TV(w); else if(type == 2) s[i] = new WashMachine(w); else if(type == 3) s[i] = new AirConditioner(w); } } public int getWeight(){//獲取家電總質量 for(int i = 0;i < n;i ++) weight += s[i].getWeight(); return weight; } } public class Main { public static void main(String [] args){ Truck t = new Truck(); t.getCount(); System.out.println(t.getWeight()); } }