THINK FIRST·CODE LATER

← All labs

Complex numbers that can be compared

Problem

A complex number a + bi has a real part a and an imaginary part b. Write an immutable class Complex implements Comparable<Complex> and a public class ComplexApp.

  • Constructors Complex(re, im) and Complex(re); accessors getRealPart(), getImaginaryPart().
  • add, subtract, multiply, divide — each returns a new Complex: (a + bi)(c + di) = (ac − bd) + (bc + ad)i and (a + bi)/(c + di) = ((ac + bd) + (bc − ad)i) / (c² + d²).
  • abs() = √(a² + b²), the distance from the origin.
  • compareTo orders complex numbers by their absolute value.
  • toString(): 3.50 + 5.50i, 3.50 - 5.50i, or just 3.50 when the imaginary part is 0.

main reads a b c d. For the input

3.5 5.5 -3.5 1

the program prints

(3.50 + 5.50i) + (-3.50 + 1.00i) = 0.00 + 6.50i
(3.50 + 5.50i) - (-3.50 + 1.00i) = 7.00 + 4.50i
(3.50 + 5.50i) * (-3.50 + 1.00i) = -17.75 - 15.75i
(3.50 + 5.50i) / (-3.50 + 1.00i) = -0.51 - 1.72i
|3.50 + 5.50i| = 6.519 and |-3.50 + 1.00i| = 3.640
The second is closer to the origin

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

3.5 5.5 -3.5 1
What your program must print for l15-7-data-1.txt
(3.50 + 5.50i) + (-3.50 + 1.00i) = 0.00 + 6.50i
(3.50 + 5.50i) - (-3.50 + 1.00i) = 7.00 + 4.50i
(3.50 + 5.50i) * (-3.50 + 1.00i) = -17.75 - 15.75i
(3.50 + 5.50i) / (-3.50 + 1.00i) = -0.51 - 1.72i
|3.50 + 5.50i| = 6.519 and |-3.50 + 1.00i| = 3.640
The second is closer to the origin

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

Windows PowerShell does not understand <:

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