SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Introduction To Parameters And Objects
Exercise:
Programming Projects
Question:4 | ISBN:9780136091813 | Edition: 2

Question

Write a program that prompts for the lengths of the sides of a triangle and reports the three angles.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.