Java Program to Calculate the Area of a Triangle

Program 1: Using Scanner Class

//importing java packages
import java.util.Scanner;

public class TriangleArea3{
  public static void main (String[] args){
    //creating new Scanner
    Scanner sc = new Scanner (System.in);

    System.out.println ("Please enter the base of the triangle:\n");
    double base = sc.nextDouble();
    System.out.println ("Please enter the heighth of the triangle:\n");
    double height = sc.nextDouble();

    //calculate area of triangle
    double area = (base * height) / 2;
    System.out.println("Area of triangle is: "+area);
  }
}

Save this file as 'TriangleArea3.java'
Compile: $javac TriangleArea3.java
Execute: $java TriangleArea3
Output:

Please enter the base of the triangle:

203
Please enter the heighth of the triangle:

137

Area of triangle is: 13905.5

Program 2: Using BufferedReader Class

//importing java packages
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class TriangleArea4{
  public static void main (String[] args)
  throws IOException{
    //creating new InputStreamReader
    InputStreamReader is = new InputStreamReader (System.in);
    //creating new BufferedReader
    BufferedReader br = new BufferedReader (is);

    System.out.println ("Please enter the base of the triangle:\n");
    int base = Integer.parseInt (br.readLine());
    System.out.println ("Please enter the heighth of the triangle:\n");
    int height = Integer.parseInt (br.readLine());

    //calculate area of triangle
    double area = (int) base * (int) height / 2; //type casting
    System.out.println("Area of triangle is: "+area);
  }
}

Save this file as 'TriangleArea4.java'
Compile: $javac TriangleArea4.java
Execute: $java TriangleArea4
Output:

Please enter the base of the triangle:

20
Please enter the heighth of the triangle:

12
Area of triangle is: 120.0


Previous: Java Program to Swap Two Numbers without using Third Variable