Challenge: Shape Areas

Lab Java Intermediate 20 points

Write an abstract class Shape with an abstract method double area(), and two children: Circle (radius) and Rect (width, height). Read n shapes, each either circle r or rect w h, and print each area with 2 decimals, then the total.

Input

First n, then n lines.

Output

n lines with an area each (2 decimals), then Total: <sum> (2 decimals).

Example

Input

2
circle 1
rect 2 3

Output

3.14
6.00
Total: 9.14
Sample input available Sample output available
Editor
Java

Hints

Each child must write area().

Store each shape in a Shape variable and call area() on it.

Solution explanation

The abstract class forces every shape to have area(), so the main loop can treat them all the same way.

Show solution
import java.util.Scanner;

abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}

class Rect extends Shape {
    double w, h;
    Rect(double w, double h) { this.w = w; this.h = h; }
    double area() { return w * h; }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        double total = 0;
        for (int i = 0; i < n; i++) {
            String kind = sc.next();
            Shape s = kind.equals("circle") ? new Circle(sc.nextDouble()) : new Rect(sc.nextDouble(), sc.nextDouble());
            System.out.printf("%.2f%n", s.area());
            total += s.area();
        }
        System.out.printf("Total: %.2f%n", total);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD