面向对象,通过键盘录入事件来计算长方形的周长面积,
需求:定义一个长方形类,定义求周长和面积的方法,然后定义一个测试类进行测试。
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//键盘录入长方形的长
Scanner sc = new Scanner(System.in);
System.out.println("请输入长方形的长");
int length = sc.nextInt();
//键盘录入长方形的宽
System.out.println("请输入长方形的宽");
int width = sc.nextInt();
// 第一种方法
//通过创建对象 调用setXXX getXXX方法输出结果
ChangFangXing c = new ChangFangXing();
c.setLength(length);
c.setWidth(width);
System.out.println("长方形的周长为:" + c.getZhouChang());
System.out.println("长方形的面积为:" + c.getMianJi());
System.out.println("-----------------------------------");
// 第二种方法
//创建对象, 通过调用构造方法,来输出结果
ChangFangXing c1 = new ChangFangXing(length, width);
c1.show();
}
}
class ChangFangXing {
private int length;
private int width;
public ChangFangXing() {
}
public ChangFangXing(int length, int width) {
this.length = length;
this.width = width;
}
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 getMianJi() {
return length * width;
}
public void show() {
System.out.println("长方形的周长为:" + (length + width) * 2);
System.out.println("长方形的面积为:" + length * width);
}
}
|
|