Saturday, 11 June 2016

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

**3.19 (Compute the perimeter of a triangle) Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge.


import java.util.Scanner;
 
public class ProgrammingEx3_19 {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter three edges of the triangle:");
  double s1 = input.nextDouble();
  double s2 = input.nextDouble();
  double s3 = input.nextDouble();

  if (s1+s2>s3 && s1+s3>s2 && s2+s3>s1) {
   System.out.print("The perimeter is " + (s1 + s2 + s3));
  }
  else 
  {
    System.out.print("The input is invalid");
    System.exit(0);
  } 
 
 }
 
}

2 comments :

  1. This code is wrong.
    /*if (s1 > s2 + s3 || s2 > s1 + s3 || s3 > s1 + s2) */
    should be
    /*if ((edge1 < edge2 + edge3) && (edge2 < edge1 + edge3) && (edge3 < edge2 + edge1))*/

    ReplyDelete
  2. @Unknown thank you for pointing out the mistake. I have fixed the code. And is accordance with Triangle Inequality Theorem. Which states that the sum of two sides of a triangle must be greater than the third side. If this is true for all three combinations, then you will have a valid triangle.

    ReplyDelete