In: Computer Science
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement the compareTo method to compare the triangles on the basis of similarity.
Draw the UML diagram for your classes.
Write a Driver class (class which instantiates the comparableTriangle objects) to determine if two instances of ComparableTriangle objects are similar (sample output below). It should prompt the user to enter the 3 sides of each triangle and then display whether or not the are similar triangle. (25 points)
Triangle Similarity: With the Triangle class we have already built, one that uses only side lengths, not angles, in its constructor, there is only one way we can check for similarity: side-side-side similarity. The definition of side-side-side similaritry is:
If all the sides of a triangle are proportional to the corresponding sides of another triangle then the triangles are said to be similar.
in other words: (Triangle1 side1 / Triangle2 side 1) = (Triangle1 side2 / Triangle2 side2) = (Triangle1 side3 / Triangle2 side3)
Java code and screen short of output and Uml diagram shown below
import java.util.*;
class Triangle //super class
{
double side1,side2,side3;
}
class comparableTriangle extends Triangle implements
Comparable<comparableTriangle>{
//subclass of Triangle that implement Comparable intefrface
comparableTriangle(double side1,double side2,double
side3){//constructor that initialize variable
this.side1=side1;
this.side2=side2;
this.side3=side3;
}
public int compareTo(comparableTriangle ct)//return 1 if both
triangle are similar
{
if((side1/ct.side1)==(side2/ct.side2)&&(side2/ct.side2)==(side3/ct.side3))
//similarity checking
return 1;
else
return 0;
}
}
public class Main//main class that read user input
{
public static void main(String[] args) {
double side1,side2,side3;
Scanner input = new Scanner (System.in); //reading
input using Scanner class
System.out.println("Enter three sides of first
triangle:");//reading first triangle
side1 = input.nextDouble();
side2 = input.nextDouble();
side3 = input.nextDouble();
//first object created and calling constructor with
values of sides
comparableTriangle c1=new
comparableTriangle(side1,side2,side3);
System.out.println("Enter three sides of second
triangle:");//reading second triangle
side1 = input.nextDouble();
side2 = input.nextDouble();
side3 = input.nextDouble();
//second object created and calling constructor with
values of sides
comparableTriangle c2=new comparableTriangle(side1,side2,side3);
if(c2.compareTo(c1)==1)//similarity checking
System.out.println("Triangles are similar");
else
System.out.println("Triangles are not similar");
}
}
output
Enter three sides of first triangle:
14 15 16
Enter three sides of second triangle:
14 15 16
Triangles are similar
Enter three sides of first triangle:
14 18 16
Enter three sides of second triangle:
14 15 16
Triangles are not similar
screen short of ouput
Uml diagram shown below