Saturday, June 21, 2014

Java Exercise Nr. 44 (Selections)

Write a program that prompts the user to enter the center coordinates and radius of two circles and determines whether the second circle 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, r1;
double x2, y2, r2;
double distanceBetweenTwoCenters;

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

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

distanceBetweenTwoCenters = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);

if(distanceBetweenTwoCenters <= r1 - r2) {
System.out.print("circle2 is inside circle1.");
} else if(distanceBetweenTwoCenters <= r1 + r2) {
System.out.print("circle2 overlaps circle1.");
} else {
System.out.print("circle2 does not overlap circle1.");
}
}

No comments:

Post a Comment

Author