THINK FIRST·CODE LATER

← All labs

Discounts through an interface

Problem

Write an interface Discountable with a constant MAX_RATE = 0.5, an abstract method double discountRate() and a default method double discountOn(double price) that returns price × min(rate, MAX_RATE).

Write an abstract class Item (name, price, finalPrice() that applies the discount only if this instanceof Discountable) and three subclasses:

  • Book — never discounted (does not implement the interface);
  • Food(name, price, daysToExpiry) — implements it: 60 % when ≤ 1 day left (capped at 50 %), 30 % when ≤ 3 days, else 0;
  • Electronics(name, price, openBox) — implements it: 15 % if open box, else 5 %.

Checkout.main reads book NAME PRICE, food NAME PRICE DAYS or tech NAME PRICE true|false until the end of input, prints each line (%-12s %8.2f plus (-3.00) if discounted), Total …, you saved … and 2 of 3 items can be discounted.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l15-4-data-1.txt

book Java 89
food Milk 12 1
food Bread 10 3
tech Mouse 120 true
What your program must print for l15-4-data-1.txt
Java            89.00
Milk             6.00  (-6.00)
Bread            7.00  (-3.00)
Mouse          102.00  (-18.00)
Total 204.00, you saved 27.00
3 of 4 items can be discounted

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l15-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content l15-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.