Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Puzzel -tringle question required for exam prepration

Write a function that receives three integer inputs for the lengths of the sides of a triangle and returns
one of four values to determine the triangle type.

1. Scalene
2. Isosceles
3. Equilateral
4. Error
by

1 Answer

iamabhishek
Try this,

public class TriangleType {

public static void main(String[] args) {
int side1 = 3;
int side2 = 4;
int side3 = 5;

int result = checkTriangleType(side1, side2, side3);

switch (result) {
case 1:
System.out.println("Scalene Triangle");
break;
case 2:
System.out.println("Isosceles Triangle");
break;
case 3:
System.out.println("Equilateral Triangle");
break;
case 4:
System.out.println("Error: Not a valid triangle");
break;
}
}

public static int checkTriangleType(int side1, int side2, int side3) {
if (side1 > 0 && side2 > 0 && side3 > 0) {
if ((side1 + side2 > side3) && (side2 + side3 > side1) && (side3 + side1 > side2)) {
if (side1 == side2 && side2 == side3) {
return 3; // Equilateral Triangle
} else if (side1 == side2 || side2 == side3 || side3 == side1) {
return 2; // Isosceles Triangle
} else {
return 1; // Scalene Triangle
}
} else {
return 4; // Error: Not a valid triangle
}
} else {
return 4; // Error: Not a valid triangle (negative side length)
}
}
}

Login / Signup to Answer the Question.