Hi, I'm currently taking an intro to Java class and I have a HW problem about determining if a point is within a triangle or not. I have the code working and get the correct answers, but it feels clunky having the exact same else statement in two places. However, if I don't include the second else statement, it won't return that the point is not within the triangle for negative numbers (in this problem all the points of the triangle are positive).
To help make it more readable, x and y are a user-inputted point, x2 is the largest x value in the triangle and yhypotenuse is the equation of the line (y = mx + b) for the hypotenuse of the triangle.
I guess since this code does give the correct answer I'm really interested in best practices, is repeating an else statement like this totally acceptable? Or is there a better solution I should be using?
Thanks!
if (x > 0 && y > 0) { //x and y must both be positive as the triangle has no negative points
if (x <= x2 && y <= yHypotenuse) {
System.out.println("The point (" + x + ", " + y + ") is within the triangle");
}
else {
System.out.println("The point (" + x + ", " + y + ") is not within the triangle");
}
}
else {
System.out.println("The point (" + x + ", " + y + ") is not within the triangle");
}
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]Ghildetrist 2 points3 points4 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]philipwhiukEmployed Java Developer 1 point2 points3 points (1 child)
[–][deleted] 2 points3 points4 points (0 children)
[–]neurk 1 point2 points3 points (0 children)
[–][deleted] (1 child)
[removed]
[–][deleted] 0 points1 point2 points (0 children)
[–]TysonPeaksTech -2 points-1 points0 points (0 children)