Saturday 20 August 2016

Chapter 6 Exercise 19, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*6.19 (The MyTriangle class) Create a class named MyTriangle that contains the following two methods:

 /** Return true if the sum of any two sides is greater than the third side. */
 public static boolean isValid( double side1, double side2, double side3)

 /** Return the area of the triangle. */
public static double area( double side1, double side2, double side3)

Write a test program that reads three sides for a triangle and computes the area if the input is valid. Otherwise, it displays that the input is invalid. The formula for computing the area of a triangle is given in Programming Exercise 2.19.

import java.util.Scanner;
 
public class MyTriangle {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter three edges of the triangle:");
  double side1 = input.nextDouble();
  double side2 = input.nextDouble();
  double side3 = input.nextDouble();
 
  if (!isValid(side1, side2, side3)) {
   System.out.print("The input is invalid");
   System.exit(0);
  }
 
  System.out.print("The area of the triangle is  "
    + area(side1, side2, side3));
 
 }
 
 public static boolean isValid(double side1, double side2, double side3) {
  return !(side1 > side2 + side3 || side2 > side1 + side3 || side3 > side1
    + side2);
 }
 
 public static double area(double side1, double side2, double side3) {
  double s = (side1 + side2 + side3) / 2;
  double area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
 
  return area;
 }
}

No comments :

Post a Comment