如果类的所有实例都包含一个相同的常量属性,则可以把这个属性定义为静态常量类型,从而节省内存空间。例如,在类中定义一个静态常量 PI。
【问题描述】定义三个类Circle,Cylinder和主类,圆周率=3.14
Circle类:
属性:
double radius;
double area;
方法有:
Circle(double radius),Circle类的构造方法。
double getArea(),计算圆面积。
Cylinder类:
属性:
Circle bottom;
double height;
方法:
Cylinder(Circle bottom, double height),Cylinder类的构造方法。
double getVolme(),计算圆柱体的体积。
主类:
输入圆半径和柱体高,输出圆柱体体积。
【输入形式】请输入底面圆形的半径。如果半径小于0,就将半径设为0。
请输入圆柱体的高。如果高小于0,就将高设为0。
【输出形式】求圆柱体的体积。
【样例输入1】
please input the radius of the circle
-2
The radius is not less than 0.
please input the height of the cylinder
3
【样例输出1】
The volume is: 0.0
【样例输入2】
please input the radius of the circle
5
please input the height of the cylinder
-3
The height is not less than 0.
【样例输出2】
The volume is: 0.0
【样例输入3】
please input the radius of the circle
2
please input the height of the cylinder
3
import java.util.Scanner;
class Circle{
double radius;
double area;
Circle(double radius) {
if (radius<0)
{
System.out.println("The radius is not less than 0.");
this.radius=0;
}
else{
this.radius=radius;
}
}
double getArea(){
area=3.14*radius*radius;
return area;
}
}
class Cylinder{
Circle bottom;
double height;
Cylinder(Circle bottom, double height)
{
if (height<0)
{
System.out.println("The height is not less than 0.");
this.height=0;
this.bottom=bottom;
}
else{
this.bottom=bottom;
this.height=height;
}
}
double getVolme(){
return bottom.getArea()*height;
}
}
public class yuanzhu {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("please input the radius of the circle");
double radius=in.nextDouble();
Circle x=new Circle(radius);
System.out.println("please input the height of the cylinder");
double height=in.nextDouble();
Cylinder y=new Cylinder(x,height);
Double v=y.getVolme();
System.out.println("The volume is: "+v ); ;
}
}