1. Introduction
Calculating the area of a triangle is a foundational task that introduces beginners to the utilization of mathematical formulas, user input, and various other aspects in Java programming. The formula to find the area of a triangle is Area = (base * height) / 2, where base represents the base length of the triangle and height represents the height of the triangle.
2. Program Steps
1. Import the Scanner class from the java.util package for user input.
2. Define the main class named TriangleArea.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class to take user input.
5. Prompt the user to enter the base length of the triangle and store it in a variable.
6. Prompt the user to enter the height of the triangle and store it in a variable.
7. Calculate the area of the triangle using the formula Area = (base * height) / 2.
8. Print the calculated area to the console.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner class for user input
public class TriangleArea { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input
System.out.print("Enter the base of the triangle: "); // 5. Prompting user for the base length
double base = input.nextDouble(); // Storing the base length in variable base
System.out.print("Enter the height of the triangle: "); // 6. Prompting user for the height
double height = input.nextDouble(); // Storing the height in variable height
double area = (base * height) / 2; // 7. Calculating the area using the formula Area = (base * height) / 2
System.out.println("The area of the triangle with base " + base + " and height " + height + " is: " + area); // 8. Printing the calculated area
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter the base of the triangle: 10 Enter the height of the triangle: 5 The area of the triangle with base 10.0 and height 5.0 is: 25.0
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported to facilitate user input.
– Step 2: The main class TriangleArea is defined.
– Step 3: The main method is defined inside the main class as the entry point of the Java program.
– Step 4: A Scanner object named "input" is created for reading user input.
– Step 5: The user is prompted to enter the base length of the triangle, 10, which is then stored in the variable base.
– Step 6: The user is also prompted to enter the height of the triangle, 5, which is stored in the variable height.
– Step 7: The area of the triangle is calculated using the formula Area = (base * height) / 2, and the result, 25.0, is stored in the variable area.
– Step 8: Finally, the calculated area of the triangle is printed to the console.
– The Scanner object is then closed to prevent resource leak.