java练习
创建一个满足以下条件的矩形Square类
编写一个矩形类,包括3个成员变量:长height、宽width和个数count;构建若干个矩形对象,分别输出它们的面积、周长和总个数。在main函数中,利用输入的两个参数长height和宽width分别作为矩形的长和宽,调用getArea()和getGirth()方法,计算并返回矩形的面积和周长。
输入:输入2个大于零的数,如10 20
若有一个数为负数,则运行时输出“长不能小于0”或“宽不能小于0”
public class Square {//矩形
public double height;
public double width;
public void setLen(double height,double width)throws Exception{
if(height<0) {
throw new Exception ("长不能小于0");
}else if(width<0)
throw new Exception ("宽不能小于0");
this.width=width;
this.height=height;
}
public double getWidth() {
return width; //获取宽
}
public double getHeight() {
return height; //获取长
}
public double getArea() {
return height*width;//获取面积
}
public double getGirth() {
return (height+width)*2;//获取周长
}
}
import java.util.Scanner;
public class textSqaure {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.print("=========矩形对象=========\n");
Scanner sc =new Scanner(System.in);
System.out.print("请输入长和宽(输入0结束):");
Square c1=new Square();
c1.height=sc.nextDouble();
c1.width=sc.nextDouble();
c1.setLen(c1.height,c1. width);
System.out.println("构建了长为"+c1.getHeight()+",宽为"+c1.getWidth()+"的矩形。"+"周长为"+c1.getGirth()+"面积为"+c1.getArea());
}catch(Exception e){
System.out.println(e.toString());
}
}
}
1.运行结果截图