(二)接口方式
定义用电量接口,然后定义实现该接口的电视机类、空调类、微波炉类。统一用接口变量指向实现该接口类对象,从而实现多态。
具体的:定义用电量接口Icomputequantity,有computequantity()方法。然后定义电视机tv类、空调air-conditioner类、微波炉microwave-oven类,都实现此接口,另外它们都有品牌名、功率、时间等私有域。不同类型或相同类型的设备如果品牌不同,功率可能都不同;
要求main方法中至少包含如下形式代码(这些语句不要求必须放在一起):
Icomputequantity ic;
ic=new tv(……);
ic=new air-conditioner(……);
ic=new microwave-oven(……);
ic.computequantity();
注:……表示参数列表
Input
有N组数据。每组数据由一个字符、一个字符串和一个整型数组成,第一个如何是’T’表示电视;是’A’表示空调;是’M’表示微波炉。而后是设备品牌字符串,然后是功率和时间,都是浮点数。
Output
每种设备的耗电量。保留两位小数,参见样例。
Sample Input
T sony 100 20
A aier 200 20
M simens 80 20
Sample Output
sony:2000.00
aier:4000.00
simens:1600.00
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double power, time;
char s;
while (in.hasNext()) {
s = in.next().charAt(0);
Icomputequantity ic;
if (s == 'T') {
String S = in.next();
power = in.nextDouble();
time = in.nextDouble();
ic = new tv();
ic.sc(S);
ic.computequantity(power, time);
}
if (s == 'A') {
String S = in.next();
power = in.nextDouble();
time = in.nextDouble();
ic = new air();
ic.sc(S);
ic.computequantity(power, time);
}
if (s == 'M') {
String S = in.next();
power = in.nextDouble();
time = in.nextDouble();
ic = new mic();
ic.sc(S);
ic.computequantity(power, time);
}
}
}
}
interface Icomputequantity {
void computequantity(double power, double time);
void sc(String S);
}
class tv implements Icomputequantity {
double power;
double time;
@Override
public void sc(String S) {
// TODO Auto-generated method stub
System.out.print(S + ":");
}
@Override
public void computequantity(double power, double time) {
// TODO Auto-generated method stub
double t = time * power;
System.out.printf("%.2f\n", t);
}
}
class air implements Icomputequantity {
double power;
double time;
@Override
public void sc(String S) {
// TODO Auto-generated method stub
System.out.print(S + ":");
}
@Override
public void computequantity(double power, double time) {
// TODO Auto-generated method stub
double t = time * power;
System.out.printf("%.2f\n", t);
}
}
class mic implements Icomputequantity {
double power;
double time;
@Override
public void sc(String S) {
// TODO Auto-generated method stub
System.out.print(S + ":");
}
@Override
public void computequantity(double power, double time) {
// TODO Auto-generated method stub
double t = time * power;
System.out.printf("%.2f\n", t);
}
}