定义一个圆柱类Cylinder
里面包含私有属性 private int radius(半径),height(高)
为属性完成其setter getter方法
完成带参构造方法Cylinder(int radius,height),该方法中包含一句System.out.println("Constructor with para");
完成无参构造方法Cylinder(),在无参构造方法中调用有参构造方法,为半径和高赋值为2,1,该方法包含一句System.out.println("Constructor no para");
完成求体积方法 public int getVolumn(){} 求圆柱体积,π使用Math.PI
- 定义测试类Main,在main方法中,按照顺序要求完成下列操作
- 从键盘接收两个数,第一个为半径,第二个为高,并利用刚才输出两个数创建圆柱体对象c1,求c1的体积并输出。
- 使用无参构造方法 创建第二个圆柱体对象c2,求c2的体积并输出。
输入格式:
在一行中输入半径 和高。
输出格式:
对每一个圆柱体输出它的体积
输入样例:
在这里给出一组输入。例如:
2 3
输出样例:
在这里给出相应的输出。例如:
Constructor with para
37
Constructor with para
Constructor no para
12
具体代码实现如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int radius = sc.nextInt();
int height = sc.nextInt();
Cylinder c1 = new Cylinder(radius,height);
System.out.println(c1.getVolumn());
Cylinder c2 = new Cylinder();
System.out.println(c2.getVolumn());
}
}
class Cylinder {
private int radius;
private int height;
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Cylinder (int radius , int height){
this.radius = radius;
this.height = height;
System.out.println("Constructor with para");
}
public Cylinder(){
this(2,1);
System.out.println("Constructor no para");
}
//求体积 公式 pi*r*r*h
public int getVolumn(){
double a;
a = (radius * radius * height) * Math.PI;
int b = (int) a;
return b;
}
}