Question: In java, how can I combine the two contains methods into one method boolean contains(Square b)? One solution was provided, but it didn't take into

In java, how can I combine the two "contains" methods into one method "boolean contains(Square b)"? One solution was provided, but it didn't take into account that the "intersects" method would no longer work correctly if implemented that way because they are inter-dependent. So I am asking for a second piece of advice. Thanks for any ideas.

import java.util.Scanner;

public class Square { private double x, y, length; public Square(double x, double y, double length) { this.x = x; this.y = y; this.length = length; }

public double area() { return length * length; }

public double perimeter() { return 4 * length; } public boolean intersects(Square b) { if (this.contains(b.x, b.y) || this.contains(b.x + b.length, b.y) || this.contains(b.x, b.y + b.length) || this.contains(b.x + b.length, b.y + b.length)) { return true; } if (b.contains(x, y) || b.contains(x + length, y) || b.contains(x, y + length) || b.contains(x + length, y + length)) { return true; } return false; }

public boolean contains(Square b) { if (this.contains(b.x, b.y) && this.contains(b.x + b.length, b.y) && this.contains(b.x, b.y + b.length) && this.contains(b.x + b.length, b.y + b.length)) { return true; } return false; } private boolean contains(double xx, double yy) { if (xx >= x && xx <= (x + length) && yy >= y && yy <= (y + length)) { return true; } return false; }

public void draw() { StdDraw.square(x + length / 2, y + length / 2, length / 2); }

public static void main(String[] args) { double x1 = Double.parseDouble(args[0]); double y1 = Double.parseDouble(args[1]); double len1 = Double.parseDouble(args[2]); Square square1 = new Square(x1, y1, len1); System.out.println("The area is " + square1.area()); System.out.println("The perimeter is " + square1.perimeter()); Scanner sc = new Scanner(System.in); System.out.print("Enter the upper-left coordinates and the length of a square: "); double x2 = sc.nextDouble(); double y2 = sc.nextDouble(); double len2 = sc.nextDouble(); Square square2 = new Square(x2, y2, len2); if (square2.intersects(square1)) { System.out.println("It intersects the first square."); } else { System.out.println("It does not intersect the first square."); } if (square2.contains(square1)) { System.out.println("It contains the first square."); } else { System.out.println("It does not contain the first square."); } square1.draw(); square2.draw(); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!