Reputation: 11
I am trying to write java program to see if a triangle is scalene, isosceles, equilateral or not a triangle. With the integers I used it is supposed to be not a triangle (1, 1, 30). But I keep getting scalene and not a triangle together. Any help is appreciated! Thank you!
public class Tri {
static void checkTriangle(int x, int y, int z)
{
// Check for equilateral triangle
if (x == y && y == z )
System.out.println("Equilateral Triangle");
// Check for isoceles triangle
else if (x == y || y == z || z == x )
System.out.println("Isoceles Triangle");
// Check for scalene triangle
else if (x != y || y!= z || z != x)
System.out.println("Scalene Triangle");
{
// Check for not a triangle
if (x + y < z || x + z < y || y + z > x)
System.out.println("Not a triangle");
}
}
public static void main(String[] args) {
{
int x = 1, y = 1, z = 30;
checkTriangle(x, y, z);
}
}
}
Upvotes: 0
Views: 5996
Reputation: 1090
Adding to the existing answer:
You should check whether a triangle can be formed or not first, then only you should check whether its scalene, isoceles or equilateral.
The order you should check in is :
Why this order?
Every triangle is a scalene triangle. Every equilateral is also an isoceles and scalene triangle.
Scalene triangle is superset of isoceles triangle and equilateral triangle. Isoceles triangle is superset of Equilateral traingle.
so your function would look like this:
static void checkTriangle(int x, int y, int z)
{
//Checking for whether its a triangle first
// Check for not a triangle
if (x + y < z || x + z < y || y + z > x) {
System.out.println("Not a triangle");
} else {
// Check for equilateral triangle
if (x == y && y == z )
System.out.println("Equilateral Triangle");
// Check for isoceles triangle
else if (x == y || y == z || z == x )
System.out.println("Isoceles Triangle");
// Check for scalene triangle
else if (x != y || y!= z || z != x)
System.out.println("Scalene Triangle");
}
}
Upvotes: 0
Reputation: 4582
You should check for not a triangle condition first. As below:
static void checkTriangle(int x, int y, int z)
{
// Check for not a triangle
if (x + y < z || x + z < y || y + z > x) {
System.out.println("Not a triangle");
} else {
// Check for equilateral triangle
if (x == y && y == z )
System.out.println("Equilateral Triangle");
// Check for isoceles triangle
else if (x == y || y == z || z == x )
System.out.println("Isoceles Triangle");
// Check for scalene triangle
else if (x != y || y!= z || z != x)
System.out.println("Scalene Triangle");
}
}
public static void main(String[] args) {
{
int x = 1, y = 1, z = 30;
checkTriangle(x, y, z);
}
}
}
Upvotes: 2