Site icon TestingDocs.com

Program to find the Triangle Type with the numbers?

Problem Statement

Given three numbers a,b,c. Write a class and a driver program to determine the Triangle Type the numbers would form.

Lets us write a program to determine the type of Triangle given the sides. We know that, if all the sides are equal the triangle is called the Equilateral triangle.  If any two sides are equal the triangle is called Isosceles Triangle etc.

Tools Used

Tools and the Environment used to develop the program are as follows.

Triangle Class

In this tutorial, We will use BlueJ Editor to code the Triangle class. The Main class is the driver. It instantiates the Triangle class. The Triangle class determines the triangle type and prints the result on the console.

 

 

public class Triangle {

private int a;
 private int b;
 private int c;

// Constructor 
 // example : Triangle triangle = new Triangle(6,5,7);
 public Triangle(int s1, int s2, int s3) {
 this.a = s1;
 this.b = s2;
 this.c = s3;
 }
 
 
 public String findTriangleType() {
 String triangleType=""; 
 // sides should be positive 
 if (a <= 0 || b <= 0 || c <= 0) {
 System.out.println("At least one side is negative\n"); 
 }
 
 // Check for side length
 if ((a + b <= c) || (a + c <= b) || (b + c <= a)) {
 System.out.println("Please check. Given sides do not form a triangle\n");
 } 
  
 if ((a == b) && (b == c)) {
 triangleType = "Equilateral Triangle";
 } else if (( a == b) || (b == c) || (a == c)) {
 triangleType = "Isosceles Triangle";
 } else {
 triangleType = "Scalene Triangle";
 } 
 
 return triangleType; 
 }

}

 

Main Class

This is driver class with the main method.

public class Main {

public static void main(String[] args) {
 Triangle triangle = new Triangle(6, 8, 8);
 System.out.println("Given Triangle type:"+ triangle.findTriangleType());
 }

}

 

Compile and run the program. Using BlueJ IDE, you can even inspect the object and execute the methods on the objects interactively.

Inspecting the Triangle class/object.

Once you have written the class, you can choose Inspect menu option to inspect the class. Right click on the Triangle class >> Inspect option.

 

 

Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version