/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * Circle.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 2-1: * Write a Circle Class that is similar to the Rect class. Define a move() * method and an isInside() method (Recall that a circle is defined as all * points within a given radius from the center. Test for insideness by using * the Pythagorean theorem to copmute the distance between a point and the * center of the circle.) Also, define a boundingBox() method that returns * the smallest Rect that encloses the complete Circle. Write a simple program * to test the methods you've implemented. * * @author Matthew Feldt * @version 1.0, 01/28/2001 9:09 */ package com.feldt.examples.classes; import com.davidflanagan.examples.classes.Rect; class Circle { private int h, k, r; Circle(int x, int y, int radius) { h = x; k = y; r = radius; } public void move(int deltax, int deltay) { h += deltax; k += deltay; } public boolean isInside(int x, int y) { // standard equation of a circle // square(x - h) + square(y - k) = square(r) x -= h; x *= x; y -= k; y *= y; return ((x + y) < (r * r)); } public Rect boundingBox() { return new Rect(h-r, k-r, h+r, k+r); } public String toString() { return "[" + h + ", " + k + "; " + r + "]"; } /** test class */ static class Test { public static void main (String args[]) { /* * create a circle and its respective bounding rectangle then * print both - tests Circle.boundingBox() & Circle.toString() */ Circle c = new Circle(0, 0, 5); Rect r = c.boundingBox(); System.out.println("Circle(0, 0, 5).toString(): " + c); System.out.println("boundingBox Rect: " + r); // test Circle.isInside() System.out.println("Circle" + c + " isInside(2, 2) = " + c.isInside(2, 2)); System.out.println("Circle" + c + " isInside(1, 5) = " + c.isInside(1, 5)); // test Circle.move() c.move(3, 3); System.out.println("c.move(3, 3): " + c); // test Circle.isInside() after move System.out.println("Circle" + c + " isInside(5, 5) = " + c.isInside(5, 5)); System.out.println("Circle" + c + " isInside(4, 8) = " + c.isInside(4, 8)); } } }