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 {       //抽象类
    private 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);
    }

    public int getTotal() {
        int total = 12;
        if (getWeight() > 1) {
            total += (getWeight() - 1) * 2;
        }
        return total;
    }
}

class DDExpress extends Express {
    public DDExpress(int weight) {
        super(weight);
    }

    public int getTotal() {
        int total = 5;
        if (getWeight() > 1) {
            total += (getWeight() - 1) * 1;
        }
        return total;
    }
}

class CaicaiStation {
    public static int calculate(Express[] ex) {
        int total = 0;
        for (Express e : ex) {
            total += e.getTotal();
        }
        return total;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值