现需要编写一个简易快递计价程序。具体来说: 1、抽象快递类Express,其包含一个属性int weight表示快递重量(单位为kg),一个方法getWeight()用于返回快递重量和一个抽象方法getTotal()用于计算快递运费。 2、两个类继承Express,分别是: (a)顺路快递SLExpress:计价规则为首重(1kg)12元,每增加1kg费用加2元。 (b)地地快递DDExpress:计价规则为首重(1kg)5元,每增加1kg费用加1元。 3、Main: 接收用户通过控制台输入的N行信息,自动计算所有快递的运费总和。
时间: 2024-03-05 22:54:41 浏览: 57
好的,以下是一个简易的快递计价程序的实现,你可以参考一下:
```java
import java.util.Scanner;
abstract class Express {
protected int weight;
public int getWeight() {
return weight;
}
public abstract int getTotal();
}
class SLExpress extends Express {
public SLExpress(int weight) {
this.weight = weight;
}
public int getTotal() {
if (weight <= 1) {
return 12;
} else {
return 12 + 2 * (weight - 1);
}
}
}
class DDExpress extends Express {
public DDExpress(int weight) {
this.weight = weight;
}
public int getTotal() {
if (weight <= 1) {
return 5;
} else {
return 5 + (weight - 1);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int total = 0;
for (int i = 0; i < n; i++) {
String expressType = scanner.next();
int weight = scanner.nextInt();
if (expressType.equals("SL")) {
SLExpress express = new SLExpress(weight);
total += express.getTotal();
} else if (expressType.equals("DD")) {
DDExpress express = new DDExpress(weight);
total += express.getTotal();
}
}
System.out.println(total);
}
}
```
这个程序包含了一个抽象类Express和两个继承自Express的子类SLExpress和DDExpress。在Main类中,通过Scanner从控制台读取输入,根据输入的快递类型和重量创建对应的快递对象,并计算出总的运费。