Find Triangle Type Based on Sides

Triangle Inequality Theorem : This theorem states that the sum of the lengths of any 2 sides of a triangle must be greater than the third side.

Triangle Types

  1. Equilateral: Here all sides are equal
  2. Isosceles: Two sides are equal
  3. Scalene: None of the sides are equal

Steps:

  1. First check if the provided inputs are not negative or zero. A triangle side can not have negative or zero length.
  2. Then check if a valid triangle can be formed from the provided inputs by checking Triangle Inequality Theorem.
  3. Add the provided inputs to a TreeSet. So, we will have only unique values in the set.
  4. Based on size of the Set, we can figure out the triangle type.

package com.java.programs;

import java.util.Set;
import java.util.TreeSet;

public class TriangleType {

    public static String findTriangleType(double a, double b, double c) {
        if (a <= 0 || b <= 0 || c <= 0) {
            throw new IllegalArgumentException("Negtive inputs are not allowed");
        }
        //Triangle Inequality Theorem : This theorem states that the sum of the lengthsĀ 
        // of any 2 sides of a triangle must be greater than the third side.
        if ((a + b < c) || (b + c < a) || (c + a < b)) {
            throw new IllegalArgumentException("A triangle can not be formed for the provided sides");
        }
        Set < Double > uniqueValues = new TreeSet < > ();
        uniqueValues.add(a);
        uniqueValues.add(b);
        uniqueValues.add(c);
        int size = uniqueValues.size();
        switch (size) {
            // Equilateral - All three sides are equal
            case 1:
                return "Equilateral";
                // Isosceles - Two sides are equal
            case 2:
                return "Isosceles";
                // Scalene - No equal sides
            case 3:
                return "Scalene";
        }

        return "";
    }

    public static void main(String[] args) {
        try {
            System.out.println(findTriangleType(5, 5, 5));
            System.out.println(findTriangleType(4, 3, 5));
            System.out.println(findTriangleType(3, 3, 2));
            System.out.println(findTriangleType(4, 2, 1));
        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

}

Equilateral
Scalene
Isosceles
java.lang.IllegalArgumentException: 
A triangle can not be formed for the provided sides

Leave a Reply

Your email address will not be published. Required fields are marked *