1. 程式人生 > >java計算長方形的周長和麵積(類和物件)

java計算長方形的周長和麵積(類和物件)

1 1 4 1
2 3 10 6
4 5 18 20
2 2 8 4
0 0 0 0
0 0 0 0
import java.util.Scanner;
class Rect
{
 
  private int length;
  private int width;
        public Rect(int length)
        {
         this(length,length);
        }
        public Rect(int length,int width)
        {
         if (length < 0)
         {
          length = 0;
         }
      if (width < 0)
      {
       width = 0;
      }
      this.width = width;
      this.length = length;
        }
        public int length() 
        {
      return 2 * (length + width);
     }
        public int area() 
        {
      return length * width;
     }
        public String print() 
        {
      String result = length + " " + width + " " + length() + " " + area();// 控制輸出格式
      return result;
     }
}
public class Main
{
    public static void main(String args[])
    {
        Scanner reader=new Scanner(System.in);
        while(reader.hasNext())
        {
         Rect rect;
         String strData=reader.nextLine();
         String[] arrayData=strData.split(" ");
         int c=arrayData.length;
         if(c==1)
         {
          int length=Integer.parseInt(arrayData[0]);
          rect=new Rect(length);
         }
         else 
         {
    int length = Integer.parseInt(arrayData[0]);
    int width = Integer.parseInt(arrayData[1]);
    rect = new Rect(length, width);
   }
         System.out.println(rect.print());
        }
    }
}