/*
定義一個長方形類,定義 求周長和面積的方法,
然后定義一個測試了Test2,進行測試。
長方形的類:
成員變量:
長,寬
成員方法:
求周長:(長+寬)*2;
求面積:長*寬
注意:
import必須出現在所有的class前面。
*/
import java.util.Scanner;
class ChangFangXing {
//長方形的長
private int length;
//長方形的寬
private int width;
public ChangFangXing(){}
//僅僅提供setXxx()即可
public void setLength(int length) {
this.length = length;
}
public void setWidth(int width) {
this.width = width;
}
//求周長
public int getZhouChang() {
return (length + width) * 2;
}
//求面積
public int getArea() {
return length * width;
}
}
class Test2 {
public static void main(String[] args) {
//創建鍵盤錄入對象
Scanner sc = new Scanner(System.in);
System.out.println("請輸入長方形的長:");
int length = sc.nextInt();
System.out.println("請輸入長方形的寬:");
int width = sc.nextInt();
//創建對象
ChangFangXing cfx = new ChangFangXing();
//先給成員變量賦值
cfx.setLength(length);
cfx.setWidth(width);
System.out.println("周長是:"+cfx.getZhouChang());
System.out.println("面積是:"+cfx.getArea());
}
}