Advertisement
eranseg

Rectangle

Aug 25th, 2019
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. ////////////////// Rectangle Class ///////////////////////
  2.  
  3. public class Rectangle {
  4.  
  5.     // Rectangle properties
  6.     private int length;
  7.     private int width;
  8.  
  9.     public Rectangle() {
  10.         this(10, 10);
  11.     }
  12.  
  13.     public Rectangle(int length, int width) {
  14.         setLength(length);
  15.         setWidth(width);
  16.     }
  17.  
  18.     public int getLength() {
  19.         return length;
  20.     }
  21.  
  22.     public void setLength(int length) {
  23.         if(length < 0) {
  24.             System.out.println("Length of rectangle can not get a negative value");
  25.             this.length = 0;
  26.         } else {
  27.             this.length = length;
  28.         }
  29.     }
  30.  
  31.     public int getWidth() {
  32.         return width;
  33.     }
  34.  
  35.     public void setWidth(int width) {
  36.         if(width < 0) {
  37.             System.out.println("Width of rectangle can not get a negative value");
  38.             this.width = 0;
  39.         } else {
  40.             this.width = width;
  41.         }
  42.     }
  43.  
  44.     public int getPerimeter() {
  45.         return 2 * (length + width);
  46.     }
  47.  
  48.     public int getArea() {
  49.         return length * width;
  50.     }
  51.  
  52.     public void print(char c) {
  53.         for(int i = 0; i < width; i++) {
  54.             System.out.print(c);
  55.         }
  56.         System.out.println();
  57.         for(int i = 0; i < length-2; i++) {
  58.             System.out.print(c);
  59.             for(int j = 0; j < width-2; j++) {
  60.                 System.out.print(" ");
  61.             }
  62.             System.out.println(c);
  63.         }
  64.         for(int i = 0; i < width; i++) {
  65.             System.out.print(c);
  66.         }
  67.         System.out.println();
  68.     }
  69.  
  70.     public void print() {
  71.         print('*');
  72.     }
  73. }
  74.  
  75. //////////////////////////// Mani Class ///////////////////////////
  76.  
  77. public class RectangleView {
  78.     public static void main(String[] args) {
  79.         Rectangle r1 = new Rectangle(7,5);
  80.         Rectangle r2 = new Rectangle();
  81.         System.out.println("Perimeter of rectangle 1 is: " + r1.getPerimeter() + " and the area is: " + r1.getArea());
  82.         r2.print();
  83.         r1.print('$');
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement