pocjt9324
pocjt9324

Reputation: 23

Why is this equation not producing the correct return?

Here is the segment of code that I'm having trouble with. No matter if the circles intersect the program is returning that they do not intersect. What am I missing here?

if(intersectCir(xBlue, yBlue, radBlue, xRed, yRed, radRed) == true) {
         System.out.println("The blue circle intersects the red circle.");
     } else if(intersectCir(xBlue, yBlue, radBlue, xRed, yRed, radRed) != true){
         System.out.println("The blue circle does not intersect the red circle.");
     }

     if(intersectCir(xBlue, yBlue, radBlue, xGreen, yGreen, radGreen) == true) {
         System.out.println("The blue circle intersects the green circle.");
     } else if(intersectCir(xBlue, yBlue, radBlue, xGreen, yGreen, radGreen) != true){
         System.out.println("The blue circle does not intersect the green circle.");
     }

     if(intersectCir(xGreen, yGreen, radGreen, xRed, yRed, radRed) == true) {
         System.out.println("The green circle intersects the red circle.");
     } else if(intersectCir(xBlue, yBlue, radBlue, xRed, yRed, radRed) != true){
         System.out.println("The green circle does not intersect the red circle.");
     }
 }




 public static boolean intersectCir(int x1, int y1, int rad1, int x2, int y2, int rad2) {
     if(Math.sqrt(Math.pow(x1 - x2, 2)) + (Math.sqrt(Math.pow(y1 - y2, 2))) <= (rad1 + rad2));
         return true;
 }

}

Upvotes: 0

Views: 60

Answers (2)

Andreas
Andreas

Reputation: 5103

Your distance formula was mistranslated. Corrected and commented below:

  public static boolean intersectCir(int x1, int y1, int rad1, int x2, int y2, int rad2) {
    //distance formula, applied:
    //    ((x1-x2)^2+(y1-y2)^2)^0.5 <= rad1+rad2
    final int xdiff = x1 - x2;
    final int ydiff = y1 - y2;
    final int totalRad = rad1 + rad2;
    //    ((xdiff)^2+(ydiff)^2)^0.5 <= totalRad
    final int distanceSquared = xdiff * xdiff + ydiff * ydiff;//beware overflow!
    //    (distanceSquared)^0.5 <= totalRad
    //square roots are hard, better to just square both sides:
    //    distanceSquared <= totalRad^2
    return distanceSquared <= totalRad * totalRad;
  }

Upvotes: 0

Dawid Frączek
Dawid Frączek

Reputation: 11

This is your corrected method.

public static boolean intersectCir(int x1, int y1, int rad1, int x2, int y2, int rad2) {
 if(Math.sqrt(Math.pow(x1 - x2, 2)) + (Math.sqrt(Math.pow(y1 - y2, 2))) <= (rad1 + rad2))
     return true;
 else
     return false;

}

Upvotes: 1

Related Questions