(Geometry: two rectangles) 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. (You must use Scanner class to get input from user.)
Sample runs:
Enter r1’s center x-, y-coordinates, width, and height: 2.5 4 2.5 43
Enter r2’s center x-, y-coordinates, width, and height: 1.5 5 0.5 3
r2 is inside r1
Enter r1’s center x-, y-coordinates, width, and height: 1 2 3 5.5
Enter r2’s center x-, y-coordinates, width, and height: 3 4 4.5 5
r2 overlaps r1
Enter r1’s center x-, y-coordinates, width, and height: 1 2 3 3
Enter r2’s center x-, y-coordinates, width, and height: 40 45 3 2
r2 does not overlap r1
Rectangle.java
/* Two Rectangle */ // Import Scanner import java.util.Scanner; public class Rectangle { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Getting information from the user (START). // Rectangle 1 information. System.out.print("Enter the center X-coordinate of the first rectangle: "); double x1 = input.nextDouble(); System.out.print("Enter the center Y-coordinate of the first rectangle: "); double y1 = input.nextDouble(); System.out.print("Enter the width of the first rectangle: "); double w1 = input.nextDouble(); System.out.print("Enter the height of the first rectangle: "); double h1 = input.nextDouble(); // Rectangle 2 information. System.out.print("Enter the center X-coordinate of the second rectangle: "); double x2 = input.nextDouble(); System.out.print("Enter the center Y-coordinate of the second rectangle: "); double y2 = input.nextDouble(); System.out.print("Enter the width of the second rectangle: "); double w2 = input.nextDouble(); System.out.print("Enter the height of the second rectangle: "); double h2 = input.nextDouble(); // Getting information from the user (END). // Calculate the distance (START). The distance must be positive. double X1X2dist = Math.sqrt(Math.pow(x1-x2,2)); double Y1Y2dist = Math.sqrt(Math.pow(y1-y2,2)); double Wdist1 = (w1/2)+(w2/2); double Hdist1 = (h1/2)+(h2/2); double Wdist2 = Math.sqrt(Math.pow((w1/2)-(w2/2),2)); double Hdist2 = Math.sqrt(Math.pow((h1/2)-(h2/2),2)); // Calculate the distance (END). The distance must be positive. // Check does not overlap. if(X1X2dist >Wdist1 || Y1Y2dist > Hdist1){ // Does not overlap. System.out.print("The rectangles are not overlap."); // Check inside or overlap. }else if(X1X2dist <= Wdist2 && Y1Y2dist <= Hdist2){ // Check which one inside or overlap. if(w1>w2 && h1>h2){ // R2 inside R1. System.out.print("The second rectangle inside of the first rectangle."); }else if(w1<w2 && h1<h2){ // R1 inside R2 System.out.print("The first rectangle inside of the second rectangle."); }else{ // Overlap. System.out.print("The rectangles are overlap."); } }else{ // Overlap. System.out.print("The rectangles are overlap."); } } }
Yorum yapabilmek için giriş yapmalısınız.