Different kinds of parcel are priced differently, and one kind builds on another's price.
What to build
A program that prices a list of parcels and totals them.
Requirements
- Write an abstract class
Parcel(with a weight in kg and an abstractcost()), and subclassesStandard(2.50 per kg),Express(5.00 plus 4.00 per kg) andFragile, which extendsStandardand costs 20% more than a standard parcel of the same weight. - Print
KIND W kg: Cfor each parcel (C with two decimals), thentotal: T.
Input
Line 1: n. Then n lines KIND WEIGHT, KIND one of standard, express, fragile.
Output
n + 1 lines.
Constraints
1 ≤ n ≤ 50; 0 < weight ≤ 100, with at most one decimal.
Example
Input:
3
standard 2
express 1.5
fragile 2
Output:
standard 2.0 kg: 5.00
express 1.5 kg: 11.00
fragile 2.0 kg: 6.00
total: 22.00
Why it works
Each subclass prices itself, Fragile reuses Standard's price through super.cost() instead of repeating the rate, and the total loop needs to know nothing about the kinds.
Examples
Example 1 · Input
3 standard 2 express 1.5 fragile 2
Expected output
standard 2.0 kg: 5.00 express 1.5 kg: 11.00 fragile 2.0 kg: 6.00 total: 22.00
Example 2 · Input
1 express 100
Expected output
express 100.0 kg: 405.00 total: 405.00
Hints
Hint 1
abstract class Parcel with a weight and abstract double cost(); Fragile extends Standard and adds 20 percent to super.cost().
Hint 2
Keep the parcels in a Parcel[] and add up cost() in one loop.
Solution
Show one correct solution (try it yourself first)
import java.util.Scanner;
abstract class Parcel {
protected final double weight;
Parcel(double weight) {
this.weight = weight;
}
abstract double cost();
abstract String kind();
}
class Standard extends Parcel {
Standard(double weight) {
super(weight);
}
@Override
double cost() {
return 2.5 * weight;
}
@Override
String kind() {
return "standard";
}
}
class Express extends Parcel {
Express(double weight) {
super(weight);
}
@Override
double cost() {
return 5 + 4 * weight;
}
@Override
String kind() {
return "express";
}
}
class Fragile extends Standard {
Fragile(double weight) {
super(weight);
}
@Override
double cost() {
return super.cost() * 1.2;
}
@Override
String kind() {
return "fragile";
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Parcel[] parcels = new Parcel[n];
for (int i = 0; i < n; i++) {
String kind = in.next();
double w = in.nextDouble();
parcels[i] = kind.equals("express") ? new Express(w) : kind.equals("fragile") ? new Fragile(w) : new Standard(w);
}
double total = 0;
for (Parcel p : parcels) {
total += p.cost();
System.out.printf("%s %.1f kg: %.2f%n", p.kind(), p.weight, p.cost());
}
System.out.printf("total: %.2f%n", total);
}
}