import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int sum = 0; Express[] express = new Express[n]; for (int i = 0; i < n; i++) { String name = scanner.next(); if (name == "SL") { express[i] = new SLExpress(scanner.nextInt()); sum += express[i].getTotal(); System.out.println(sum); } else if(name == "DD") { express[i] = new DDExpress(scanner.nextInt()); sum += express[i].getTotal(); } } System.out.print(sum); } } abstract class Express { private int weight; Express(int weight) { this.weight = weight; } public int getWeight() { return this.weight; } public abstract int getTotal(); } class SLExpress extends Express { SLExpress(int weight) { super(weight); } public int getTotal() { int total = 0; if(super.getWeight() <= 1) total = 12; else total = 12 + (super.getWeight() - 1)*2; return total; } } class DDExpress extends Express { DDExpress(int weight) { super(weight); } public int getTotal() { int total = 0; if(super.getWeight() <= 1) total = 5; else total = 5 + (super.getWeight() - 1)*1; return total; } }
时间: 2024-04-27 07:19:51 浏览: 121
Einleser:java.util.Scanner 的示例
这段代码实现了一个简单的快递计价程序,其中用到了抽象类和多态的概念。程序中定义了一个Express抽象类,其中包含一个weight属性表示快递重量和一个getTotal()抽象方法用于计算运费。SLExpress和DDExpress类都继承自Express类,分别实现了不同的计价标准。
在main方法中,首先读入快递数量n,然后用一个Express类型的数组来保存每个快递。在循环中,先读入快递公司名称name和重量weight,根据不同的快递公司名称创建不同的快递对象并将其保存到数组中。然后调用getTotal()方法计算运费并累加到sum变量中。最后输出sum即为所有快递的总运费。
需要注意的是,在比较字符串时应该使用equals()方法而不是==运算符。因为==运算符比较的是对象的引用是否相等,而equals()方法比较的是对象的值是否相等。因此,应该将name == "SL"和name == "DD"改为name.equals("SL")和name.equals("DD")。
阅读全文