Write a program that prompts for the lengths of the sides of a triangle and reports the three angles.
Program code:
import java.util.Scanner;
public class TriangleAngles {
// Method to calculate and display the angles of a triangle
public static void calculateAngles(double side1, double side2, double side3) {
// Calculate the angles using the law of cosines
double angle1 = Math.toDegrees(Math.acos((side2 * side2 + side3 * side3 - side1 * side1) / (2 * side2 * side3)));
double angle2 = Math.toDegrees(Math.acos((side1 * side1 + side3 * side3 - side2 * side2) / (2 * side1 * side3)));
double angle3 = Math.toDegrees(Math.acos((side1 * side1 + side2 * side2 - side3 * side3) / (2 * side1 * side2)));
// Display the angles
System.out.println("Angles of the triangle:");
System.out.println("Angle 1: " + angle1 + " degrees");
System.out.println("Angle 2: " + angle2 + " degrees");
System.out.println("Angle 3: " + angle3 + " degrees");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the lengths of the sides of the triangle
System.out.print("Enter the length of side 1: ");
double side1 = scanner.nextDouble();
System.out.print("Enter the length of side 2: ");
double side2 = scanner.nextDouble();
System.out.print("Enter the length of side 3: ");
double side3 = scanner.nextDouble();
// Calculate and display the angles of the triangle
calculateAngles(side1, side2, side3);
scanner.close();
}
}
Executed Output:
Enter the length of side 1: 3.5
Enter the length of side 2: 4.5
Enter the length of side 3: 5.5
Angles of the triangle:
Angle 1: 33.709 degrees
Angle 2: 55.076 degrees
Angle 3: 91.215 degrees