在菜菜驿站类CaicaiStation中,我们需要提供一个静态方法int calculate(Express ex),用于计算所有快递的费用。可以按照以下步骤来实现:
1. 在Express类中,添加一个抽象方法getTotal(),用于计算快递运费。同时添加一个getWeight()方法,用于返回快递重量。public abstract class Express { private int weight; public Express(int weight) { this.weight = weight; } public int getWeight() { return weight; } public abstract int getTotal();}
2. 创建两个子类:SLExpress和DDExpress,分别继承Express类,并实现getTotal()方法。public class SLExpress extends Express { public SLExpress(int weight) { super(weight); } @Override public int getTotal() { int weight = getWeight(); int basePrice = 12; // 首重费用 int additionalPrice = 2; // 每增加1kg的费用 return basePrice + additionalPrice * (weight - 1); }}public class DDExpress extends Express { public DDExpress(int weight) { super(weight); } @Override public int getTotal() { int weight = getWeight(); int basePrice = 5; // 首重费用 int additionalPrice = 1; // 每增加1kg的费用 return basePrice + additionalPrice * (weight - 1); }}
3. 在CaicaiStation类中,实现静态方法calculate(Express ex),用于计算所有快递的费用。public class CaicaiStation { public static int calculate(Express ex) { return ex.getTotal(); }}
4. 在Main类中,根据用户输入的快递信息,创建对应的SLExpress或DDExpress对象,并调用CaicaiStation.calculate()方法计算费用。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 < n; i++) { if (sc.next().equals("SL")) { int weight = sc.nextInt(); ex[i] = new SLExpress(weight); } else { int weight = sc.nextInt(); ex[i] = new DDExpress(weight); } } for (int i = 0; i < n; i++) { System.out.println(CaicaiStation.calculate(ex[i])); } sc.close(); }}
这样,就可以根据用户输入的快递信息计算出对应的运费了。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。 |