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 19:53:14 浏览: 115
好的,你的问题是关于抽象快递类Express及其子类的实现,以及如何通过控制台输入来计算所有快递的运费总和。
下面是Java代码的实现:
```java
import java.util.Scanner;
// 抽象快递类
abstract class Express {
protected int weight; // 快递重量(单位为kg)
public Express(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
// 抽象方法,用于计算快递运费
public abstract double getTotal();
}
// 顺路快递类
class SLExpress extends Express {
public SLExpress(int weight) {
super(weight);
}
// 计价规则为首重(1kg)12元,每增加1kg费用加2元
public double getTotal() {
if (weight <= 1) {
return 12;
} else {
return 12 + (weight - 1) * 2;
}
}
}
// 地地快递类
class DDExpress extends Express {
public DDExpress(int weight) {
super(weight);
}
// 计价规则为首重(1kg)5元,每增加1kg费用加1元
public double getTotal() {
if (weight <= 1) {
return 5;
} else {
return 5 + (weight - 1) * 1;
}
}
}
// Main类
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 接收用户输入的N行信息
double total = 0; // 记录所有快递的运费总和
for (int i = 0; i < n; i++) {
String type = scanner.next(); // 快递类型
int weight = scanner.nextInt(); // 快递重量
// 根据快递类型创建对应的对象,并计算快递运费
Express express = null;
if (type.equals("SL")) {
express = new SLExpress(weight);
} else if (type.equals("DD")) {
express = new DDExpress(weight);
}
if (express != null) {
total += express.getTotal();
}
}
System.out.println("所有快递的运费总和为:" + total);
}
}
```
用户需要在控制台输入N行信息,每行信息包括快递类型和快递重量,比如:
```
3
SL 2
DD 3
SL 1
```
程序会根据快递类型创建对应的对象,并计算快递运费。最后输出所有快递的运费总和。以上面的输入为例,输出为:
```
所有快递的运费总和为:32.0
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)