第二章編程作業(yè) 2-1
創(chuàng)建一個簡單的表示矩形的Rectangle類,滿足以下條件:
1、定義兩個成員變量height和width,表示矩形的長和寬,類型為整型 2、定義一個getArea方法,返回矩形的面積 3、定義一個getPerimeter方法,返回矩形的周長 4、在main函數(shù)中,利用輸入的2個參數(shù)分別作為矩形的長和寬,調(diào)用getArea和getPermeter方法,計算并返回矩形的面積和周長
輸入:
輸入2個正整數(shù),中間用空格隔開,分別作為矩形的長和寬,例如:5 8
輸出:
輸出2個正整數(shù),中間用空格隔開,分別表示矩形的面積和周長,例如:40 26
代碼如下:
import java.util.Scanner;
class Rectangle {
int heigth;
int width;
public int getAera( int heigth, int width )
{
heigth = this.heigth;
width = this.width;
return heigth * width;
}
public int getPerimeter( int heigth, int width )
{
heigth = this.heigth;
width = this.width;
return (2 * (heigth + width));
}
}
public class Main {
public static void main(String[] args) {
Rectangle rec = new Rectangle();
Scanner input=new Scanner(System.in);
rec.heigth=input.nextInt();
rec.width=input.nextInt();
System.out.print(rec.getAera(rec.heigth, rec.width)+" ");
System.out.println(rec.getPerimeter(rec.heigth, rec.width));
}
}