Triangle area comparison (classes) Given class Triangle, complete the program to read and set the base and height of triangle1 and triangle2, determine which triangle's area is larger, and output the larger triangle's info, making use of Triangle's relevant methods. Ex: If the input is: 3.0 4.0 4.0 5.0 where 3.0 is triangle1's base, 4.0 is triangle1's height, 4.0 is triangle2's base, and 5.0 is triangle2's height, the output is: Triangle with larger area: Base: 4.00 Height: 5.00 Area: 10.00

Answer :

ammary456

Answer:

// Triangle.java

public class Triangle {

   private double base;

   private double height;

   public void setBase(double base) {

       this.base = base;

   }

   public void setHeight(double height) {

       this.height = height;

   }

   public double getArea() {

       return 0.5 * base * height;

   }

 

   public void printInfo() {

       System.out.printf("Base: %.2f\n", base);

       System.out.printf("Height: %.2f\n", height);

       System.out.printf("Area: %.2f\n", getArea());

   }

}

// TriangleArea.java

import java.util.Scanner;

public class TriangleArea {

   public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       double base1 = in.nextDouble();

       double height1 = in.nextDouble();

       double base2 = in.nextDouble();

       double height2 = in.nextDouble();

 

       Triangle triangle1 = new Triangle();

       triangle1.setBase(base1);

       triangle1.setHeight(height1);

       Triangle triangle2 = new Triangle();  

       triangle2.setBase(base2);

       triangle2.setHeight(height2);

       System.out.println("Triangle with larger area:");

       if (triangle1.getArea() > triangle2.getArea()) {

           triangle1.printInfo();

       } else {

           triangle2.printInfo();

       }

   }

}

Explanation:

  • Inside the getArea method, calculate the area by applying the following formula.

Area = 0.5 * base * height;

  • Get the input from user for both triangles.
  • Compare the area of both triangle and print the information of the larger triangle.

Other Questions