定义一个矩形类Rectangle:(知识点:对象的创建和使用)
1 定义三个方法:getArea()求面积、getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长。
2 有2个属性:长length、宽width
3 创建一个Rectangle对象,并输出相关信息
import java.util.Scanner; //测试类 class text{ public static void main(String[] args) { Rectangle r=new Rectangle(); System.out.println("请输入矩形长度"); Scanner sc=new Scanner(System.in); int length = sc.nextInt(); r.setLength(length); System.out.println("请输入矩形宽度"); int width = sc.nextInt(); r.setWidth(width); r.getAll(); r.getArea(); r.getPer(); } } //矩形类 public class Rectangle { private int length; private int width; public Rectangle() { } public Rectangle(int length, int width) { this.length = length; this.width = width; } public int getLength(int i) { return length; } public int getWidth() { return width; } public void setLength(int length) { this.length = length; } public void setWidth(int width) { this.width = width; } //求面积 public void getArea(){ System.out.println("面积为;"+width*length); } //求周长 public void getPer(){ System.out.println("周长为;"+(width+length)*2); } public void getAll(){ System.out.println("长度为"+length+"宽度为"+width+"面积为"+width*length+"周长为"+(width+length)*2); } }