Java面向对象基础:圆柱体类设计

定义一个圆柱类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;
    }
}

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值