Saturday, June 21, 2014

Java Exercise Nr. 43 (Selections)

Write a program that prompts the user to enter the center x-, y-coordinates, width, and height of two rectangles and determines whether the second rectangle is inside the first or overlaps with the first, as shown
in figure below.


Solution:

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x1, y1, w1, h1;
double x2, y2, w2, h2;
double distx1x2, disty1y2;
double distW, distH;

System.out.print("Enter r1's center x-, y-coordinates, width, and height:");
x1 = s.nextDouble();
y1 = s.nextDouble();
w1 = s.nextDouble();
h1 = s.nextDouble();

System.out.print("Enter r2's center x-, y-coordinates, width, and height:");
x2 = s.nextDouble();
y2 = s.nextDouble();
w2 = s.nextDouble();
h2 = s.nextDouble();

distx1x2 = Math.pow(Math.pow(x2 - x1, 2), 0.5);
disty1y2 = Math.pow(Math.pow(y2 - y1, 2), 0.5);

distW = (w1/2) + (w2/2);
distH = (h1/2) + (h2/2);

if(distx1x2 > distW || disty1y2 > distH) {
System.out.print("r2 does not overlap r1.");
} else if(distx1x2 < w1 && disty1y2 < h1 && distW < w1 && distH < h1) {
System.out.print("r2 is inside r1.");
} else {
System.out.print("r2 overlaps r1.");
}
}

No comments:

Post a Comment

Author