THINK FIRST·CODE LATER

← All labs

Money: overloaded constructors and methods

Problem

Money must never be stored in a double (0.1 + 0.2 ≠ 0.3). Write a class Money that stores whole fen in a private final long (1 yuan = 100 fen), with three overloaded constructors:

  • Money(long yuan, int fen),
  • Money(long yuan) — calls the first with this(yuan, 0),
  • Money(String text) — parses "12.5", "12.50" or "7";

and overloaded add(Money) / add(int fen), plus times(int), equals(Money) and toString() → 12.50 yuan.

MoneyApp.main reads a text amount, then yuan fen, then yuan, then a count:

a = 12.50 yuan
b = 7.50 yuan
c = 20.00 yuan
a + b = 20.00 yuan
a + 5 fen = 12.55 yuan
3 x b = 22.50 yuan
a equals b: false
a + b equals c: true

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.

l11-3-data-1.txt

12.5 7 50 20 3
What your program must print for l11-3-data-1.txt
a = 12.50 yuan
b = 7.50 yuan
c = 20.00 yuan
a + b = 20.00 yuan
a + 5 fen = 12.55 yuan
3 x b = 22.50 yuan
a equals b: false
a + b equals c: true

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 < l11-3-data-1.txt

Windows PowerShell does not understand <:

Get-Content l11-3-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.