THINK FIRST·CODE LATER

← All labs

Fraction: an immutable value class

Problem

Write a class Fraction and a public class FractionApp. A Fraction has two private final ints, num and den, and is always stored in lowest terms with a positive denominator (2/-4 becomes -1/2). Methods: add, subtract, multiply (each returns a new Fraction), toDouble(), isLessThan(Fraction) and toString() (3/4, or just 2 when the denominator is 1).

main reads four integers a b c d (the fractions a/b and c/d) and prints:

a = 1/2, b = 3/4
a + b = 5/4
a - b = -1/4
a * b = 3/8
a as decimal = 0.5000
smaller: 1/2

Write a private helper gcd for the reduction.

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.

l10-3-data-1.txt

1 2 3 4
What your program must print for l10-3-data-1.txt
a = 1/2, b = 3/4
a + b = 5/4
a - b = -1/4
a * b = 3/8
a as decimal = 0.5000
smaller: 1/2

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

Windows PowerShell does not understand <:

Get-Content l10-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.