Challenge: Payment Methods

Lab Java Intermediate 20 points

Write an interface Payment with double fee(double amount). Implement it in three classes:

  • Card: fee is 2% of the amount
  • Upi: fee is 0
  • Wallet: fee is a flat 5

Read a method name (card, upi or wallet) and an amount. Print the fee and the total to pay, both with 2 decimals.

Input

One line: method name and amount.

Output

Fee: <fee>
Total: <amount + fee>

Example

Input

card 1000

Output

Fee: 20.00
Total: 1020.00
Sample input available Sample output available
Editor
Java

Hints

Interface methods must be public in the class.

Use a Payment variable to hold whichever object you create.

Solution explanation

The code that prints the fee only knows about Payment. Adding a new payment type needs no change there.

Show solution
import java.util.Scanner;

interface Payment {
    double fee(double amount);
}

class Card implements Payment {
    public double fee(double amount) { return amount * 0.02; }
}

class Upi implements Payment {
    public double fee(double amount) { return 0; }
}

class Wallet implements Payment {
    public double fee(double amount) { return 5; }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String kind = sc.next();
        double amount = sc.nextDouble();
        Payment p;
        if (kind.equals("card")) p = new Card();
        else if (kind.equals("upi")) p = new Upi();
        else p = new Wallet();
        double fee = p.fee(amount);
        System.out.printf("Fee: %.2f%n", fee);
        System.out.printf("Total: %.2f%n", amount + fee);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD