Java实验⼀:编写Rectangle(矩形)类......
编写Rectangle(矩形)类.该类具有double类型的私有实例变量length(长)和width(宽),它们默认值都是0.0,提供带有2个参数的构造函数,以便在创建该类的对象时对其进⾏初始化;提供将实例变量设置为默认值的⽆参构造函数以便创建时可以不带初始值。该类有length和width的设置/读取⽅法,设置⽅法应验
证length和width都是正数,否则设置发法将这些变量设置为它们的默认值。该类还有计算矩形周长(perimeter)和⾯积(area)的⽅法以及toString()⽅
法,toString()⽅法返回包含矩形的长、宽、周长、⾯积的字符串。
import java.util.Scanner;
public class Rectangle{
private static double length;
private static double width;
static void set_width(double width2) {
// TODO Auto-generated method stub
if(width2<0)
width=0;
else width = width2;
}
static void set_length(double length2) {
generated// TODO Auto-generated method stub
if(length2<0)
length=0;
else length = length2;
}
static double get_length(){
return length;
}
static double get_width(){
return width;
}
static double perimeter(){
return (length+width)*2;
}
static double area(){
return length*width;
}
public static String tostring(){
//return null;
String s = "";
s = s + " length="+get_length();
s = s + " width="+get_width();
s = s + " perimeter="+perimeter();
s = s + " area="+area();
return s;
}
public static void Rectangle(double d, double e) {
/
/ TODO Auto-generated method stub
set_length(d);
set_width(e);
}
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.print("input double type length and width: ");
double length = Double();
double width = Double();
Rectangle(length,width);
System.out.print(tostring());
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论