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\\", base);
System.out.printf("Height: %.2f\\", height);
System.out.printf("Area: %.2f\\", 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();
}
}
}
Step-by-step 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.