THINK FIRST·CODE LATER

← All labs

IllegalTriangleException: an object that refuses to be built

Problem

Three lengths form a triangle only if they are all positive and the sum of any two is greater than the third. Write:

  • a checked exception IllegalTriangleException extends Exception that receives the three sides, builds the message Sides 1.0, 2.0 and 5.0 cannot form a triangle, and offers getLongestSide();
  • a class CheckedTriangle whose constructor is declared throws IllegalTriangleException and throws it for impossible sides; with getPerimeter() and getArea() (Heron's formula);
  • a public class TriangleCheck that reads triples of sides until the end of the input, tries to build each triangle, and prints either its perimeter and area or the rejection, then the totals.

For the input

3 4 5
1 2 5
2 2 2
0 4 4
10 1 1

the program prints

Triangle 3.0 4.0 5.0: perimeter 12.00, area 6.00
Rejected: Sides 1.0, 2.0 and 5.0 cannot form a triangle (longest side 5.0)
Triangle 2.0 2.0 2.0: perimeter 6.00, area 1.73
Rejected: Sides 0.0, 4.0 and 4.0 cannot form a triangle (longest side 4.0)
Rejected: Sides 10.0, 1.0 and 1.0 cannot form a triangle (longest side 10.0)
2 triangle(s) built, 3 rejected

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.

l16-5-data-1.txt

3 4 5
1 2 5
2 2 2
0 4 4
10 1 1
What your program must print for l16-5-data-1.txt
Triangle 3.0 4.0 5.0: perimeter 12.00, area 6.00
Rejected: Sides 1.0, 2.0 and 5.0 cannot form a triangle (longest side 5.0)
Triangle 2.0 2.0 2.0: perimeter 6.00, area 1.73
Rejected: Sides 0.0, 4.0 and 4.0 cannot form a triangle (longest side 4.0)
Rejected: Sides 10.0, 1.0 and 1.0 cannot form a triangle (longest side 10.0)
2 triangle(s) built, 3 rejected

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

Windows PowerShell does not understand <:

Get-Content l16-5-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.