pta-6-8 快递计价器

现需要编写一个简易快递计价程序。具体来说:

1、抽象 快递类Express,其包含一个属性int weight表示快递重量(单位为kg),一个方法getWeight()用于返回快递重量和一个抽象方法 getTotal()用于计算快递运费。

2、两个类继承Express,分别是:

(a)顺路快递SLExpress:计价规则为首重(1kg)12元,每增加1kg费用加2元。

(b)地地快递DDExpress:计价规则为首重(1kg)5元,每增加1kg费用加1元。

3、菜菜驿站类CaicaiStation,提供静态方法 int calculate(Express\[\] ex) 用于计算所有快递的费用。

输入样例:

复制代码
6
SL 2
DD 2
SL 1
SL 1
SL 1
DD 3

输入解释:

第1行n表示需要计算的快递件数

第2至n+1表示每个快递信息,即选哪家快递公司 以及快递的重量(单位kg)

输出样例:

复制代码
63

输出解释:

所有快递总运费。

裁判测试程序样例:

复制代码
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Express[] ex = new Express[n];
        for (int i = 0; i < ex.length; i++) {
            if (sc.next().equals("SL"))
                ex[i] = new SLExpress(sc.nextInt());
            else
                ex[i] = new DDExpress(sc.nextInt());
        }

        System.out.println(CaicaiStation.calculate(ex));
        sc.close();
    }
}
/* 请在这里填写答案 */

正确答案:

复制代码
// 抽象快递类
abstract class Express {
    protected int weight; // 快递重量

    public Express(int weight) {
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }

    // 抽象方法,用于计算快递费用
    public abstract int getTotal();
}

// 顺路快递类
class SLExpress extends Express {
    public SLExpress(int weight) {
        super(weight);
    }

    @Override
    public int getTotal() {
        // 首重1kg 12元,每增加1kg加2元
        return 12 + Math.max(0, weight - 1) * 2;
    }
}

// 地地快递类
class DDExpress extends Express {
    public DDExpress(int weight) {
        super(weight);
    }

    @Override
    public int getTotal() {
        // 首重1kg 5元,每增加1kg加1元
        return 5 + Math.max(0, weight - 1);
    }
}

// 菜菜驿站类
class CaicaiStation {
    // 静态方法,用于计算所有快递的费用
    public static int calculate(Express[] ex) {
        int total = 0;
        for (Express e : ex) {
            total += e.getTotal();
        }
        return total;
    }
}
相关推荐
丈剑走天涯15 分钟前
JDK 17 正式特性
java·开发语言
秋田君24 分钟前
QT_QFontDialog类字体对话框
开发语言·qt
圣光SG29 分钟前
Java操作题练习(七)
java·开发语言·算法
麻瓜老宋2 小时前
AI开发C语言应用按步走,表达式计算器calc的第二十三步,多行输入、进制输出、错误恢复、常量折叠、配置加载等
c语言·开发语言·atomcode
Cx330_FCQ2 小时前
Tmux使用
服务器·git·算法
q567315232 小时前
企业级 HTTP 代理采购选型:技术评估清单 15 项
开发语言·网络·爬虫·网络协议·http·隧道ip·代理ip
@航空母舰2 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端
天天进步20153 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
Co_Hui3 小时前
Java 并发编程
java
拳里剑气3 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs