Advertisement
sedran

Rectangle | sedran

Mar 14th, 2011
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. /**
  2.  * Create your own rectangle
  3.  * @author sedran
  4.  *
  5.  */
  6. public class Rectangle {
  7.     private int x, y, width, height;
  8.    
  9.     /**
  10.      * Construct a new rectangle
  11.      * @param x = the x value of the top left corner of the rectangle
  12.      * @param y = the y value of the top left corner of the rectangle
  13.      * @param width = width of the rectangle
  14.      * @param height = height of the rectangle
  15.      */
  16.     public Rectangle(int x, int y, int width, int height) {
  17.         this.x = x;
  18.         this.y = y;
  19.         this.width = width;
  20.         this.height = height;
  21.     }
  22.    
  23.     /**
  24.      * Get the x value of the top left corner
  25.      * @return the x value of the top left corner
  26.      */
  27.     public int getX() {
  28.         return x;
  29.     }
  30.    
  31.     /**
  32.      * Get the y value of the top left corner
  33.      * @return the y value of the top left corner
  34.      */
  35.     public int getY() {
  36.         return y;
  37.     }
  38.    
  39.     /**
  40.      * Get width of the rectangle
  41.      * @return width of rectangle
  42.      */
  43.     public int getWidth() {
  44.         return width;
  45.     }
  46.    
  47.     /**
  48.      * Get height of the rectangle
  49.      * @return height of rectangle
  50.      */
  51.     public int getHeight() {
  52.         return height;
  53.     }
  54.    
  55.     public String toString() {
  56.         return "Rectangle[x=" + x + ",y=" + y + ",width="+ width +", height="+ height +"]";
  57.     }
  58.    
  59.     public boolean contains(int x, int y) {
  60.         if(x >= this.x && x <= this.x+this.width && y <= this.y && y >= this.y-height)
  61.             return true;
  62.         return false;
  63.     }
  64.    
  65.     public Rectangle intersect(Rectangle rect) {
  66.         boolean first = false;
  67.         int x1=0, x2=0, y1=0, y2=0;
  68.         for(int i=this.x; i<=(this.x+this.width); i++) {
  69.             for(int k=this.y; k>=(this.y-this.height); k--) {
  70.                 if(rect.contains(i, k)) {
  71.                     if( !first ) {
  72.                         first = true;
  73.                         x1 = i;
  74.                         y1 = k;
  75.                     } else {
  76.                         x2 = i;
  77.                         y2 = k;
  78.                     }
  79.                 }
  80.             }
  81.         }
  82.         return new Rectangle(x1,y1,x2-x1,y1-y2);
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement