Write a Java method to calculate the area of a triangle


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise {
  3. public static void main(String[] args)
  4. {
  5. Scanner in = new Scanner(System.in);
  6. System.out.print("Input Side-1: ");
  7. double side1 = in.nextDouble();
  8. System.out.print("Input Side-2: ");
  9. double side2 = in.nextDouble();
  10. System.out.print("Input Side-3: ");
  11. double side3 = in.nextDouble();
  12. System.out.println( isValid(side1, side2,side3) ?
  13. "The area of the triangle is " + areaoftriangle(side1, side2, side3) : "Invalid triangle" );
  14. }
  15.  
  16. public static boolean isValid(double side1, double side2, double side3) {
  17. if( side1 + side2 > side3 &&
  18. side2 + side3 > side1 &&
  19. side1 + side3 > side2) return true;
  20. else return false;
  21. }
  22. public static double areaoftriangle(double side1, double side2, double side3) {
  23. double area = 0;
  24. double s = (side1 + side2 + side3)/2;
  25. area = Math.sqrt(s*(s - side1)*(s - side2)*(s - side3));
  26. return area;
  27. }
  28. }

Result

java techstudy.org

     





Related Topics




Popular Posts