Anna
Anna

Reputation: 23

Program to determine if 3 sides form a valid triangle using Java

Given three integers a, b, and c, return true if a, b, and c could be the lengths of the sides of a right triangle. Return false otherwise. Recall that in a right triangle, each side must have a positive length, and the sum of the squares of the leg lengths must equal the square of the length of the hypotenuse.

isRightTriangle(3, 4, 5) → true isRightTriangle(4, 3, 5) → true isRightTriangle(5, 4, 3) → true

boolean isRightTriangle(int a, int b, int c) {
  if(a>0 && b>0 && c>0){
    if((Math.sqrt((double)a)+Math.sqrt((double)b))==Math.sqrt((double)c)){
      return true;
    }
    else{
      if((Math.sqrt((double)b)+Math.sqrt((double)c))==Math.sqrt((double)a)){
        return true;
      }
      else{
        if((Math.sqrt(c)+Math.sqrt(b))==Math.sqrt(a)){
          return true;
        }
        else{
          return false;
        }
      }
    }
    }
  else{
    return false;
  }
}

Upvotes: 0

Views: 2052

Answers (1)

bcr666
bcr666

Reputation: 2197

You are using Math.sqrt instead of Math.pow(x, 2). You need to check that a^2+b^2=c^2, not sqrt(a)+sqrt(b)=sqrt(c).

boolean isRightTriangle(int a, int b, int c) {
  // lets exit if variables are bad
  if(a < 1 || b < 1 || c < 1) {
    return false;
  }
  // lets create an array so we can sort
  int[] arry = new int[3];
  arry[0] = a;
  arry[1] = b;
  arry[2] = c;
  Arrays.sort(arry);
  // now that the array is sorted, the largest number (the hypotenuse) should be arry[2]
  return Math.pow(arry[0], 2) + Math.pow(arry[1], 2) == Math.pow(arry[2], 2);
}

Upvotes: 0

Related Questions