The problem 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. Test your program to cover all cases.

Breaking it down public static void main ( String [] strings ) {
Scanner input = new Scanner ( System . in );
System . out
. print ( "Enter r1’s center x and y-coordinates, width, and height: " );
double x1 = input . nextDouble ();
double y1 = input . nextDouble ();
double width1 = input . nextDouble ();
double height1 = input . nextDouble ();
System . out
. print ( "Enter r2’s center x and y-coordinates, width, and height: " );
double x2 = input . nextDouble ();
double y2 = input . nextDouble ();
double width2 = input . nextDouble ();
double height2 = input . nextDouble ();
input . close ();
double xDistance = calculateDistance ( x1 , x2 );
double yDistance = calculateDistance ( y1 , y2 );
boolean r2IsInsideR1 = inside ( width1 , height1 , width2 , height2 ,
xDistance , yDistance );
boolean r2OverlapsR1 = overLaps ( width1 , height1 , width2 , height2 ,
xDistance , yDistance );
if ( r2IsInsideR1 ) {
System . out . println ( "r2 is inside r1" );
} else if ( r2OverlapsR1 ) {
System . out . println ( "r2 overlaps r1" );
} else {
System . out . println ( "r2 does not overlap r1" );
}
}
private static boolean overLaps ( double width1 , double height1 ,
double width2 , double height2 , double xDistance , double yDistance ) {
boolean r2OverlapsR1 = ( xDistance <= ( width1 + width2 ) / 2 && yDistance <= ( height1 + height2 ) / 2 );
return r2OverlapsR1 ;
}
private static boolean inside ( double width1 , double height1 , double width2 ,
double height2 , double xDistance , double yDistance ) {
boolean r2IsInsideR1 = ( xDistance <= ( width1 - width2 ) / 2 && yDistance <= ( height1 - height2 ) / 2 );
return r2IsInsideR1 ;
}
private static double calculateDistance ( double x1 , double x2 ) {
double xDistance = x1 >= x2 ? x1 - x2 : x2 - x1 ;
return xDistance ;
}

Output Geometry two rectangles posted by Justin Musgrove on 09 April 2016

Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch3

Share on: Facebook Google+