实现圆类的面积和周长计算+包装类

/*
当进行计算时返回的结果没有想要的结果时,
就用包装类返回null
再在main中进行判断有没有结果
 */



public class Homework06 {
    public static void main(String[] args) {
        Cale a1 = new Cale(2, 10);
        System.out.println("和=" + a1.he());
        System.out.println("差=" + a1.cha());
        System.out.println("乘=" + a1.cheng());
        Double num=a1.chu();
        if(num!=null){
            System.out.println("除=" + num);
        }

    }
}

/*
编程创建一个Cale计算类,在其中定义两个变量表示两个操作数,
定义四个方法实现求和、差、乘、商(要求除数为0的话,要提示)
并创建两个对象,分别测试
 */

class Cale {
    double oper1;
    double oper2;

    public Cale(double oper1, double oper2) {
        this.oper1 = oper1;
        this.oper2 = oper2;
    }

    public double he() {
        return oper1 + oper2;
    }

    public double cha() {
        return oper1 - oper2;
    }

    public double cheng() {
        return oper1 * oper2;
    }

    public Double chu() {
        //判断
        if (oper2 == 0) {
            System.out.println("oper2不能为0");
            return null;
        } else
            return oper1 / oper2;

    }

}

//public class Homework05 {
//    public static void main(String[] args) {
//        A04 a04=new A04(3);
//        a04.display();
//    }
//}
//
///*
//定义一个圆类Circle,定义属性:半径,提供显示圆周长功能的方法,提供显示圆面积的方法
// */
//
//class A04{
//    double r;
//    public A04(double r){
//        this.r = r;
//    }
//    public void display(){
//        double length=2*3.14*this.r;
//        double area=3.14*this.r*this.r;
//        System.out.println("圆的周长为"+length+"   圆的面积为"+area);
//    }
//}

public class Homework05 {
    //编写一个main方法
    public static void main(String[] args) {
        Circle circle=new Circle(3);
        System.out.println("面积="+circle.area());
        System.out.println("周长="+circle.len());

    }
}

//在Circle类中分别写了两个函数,用来返回周长和面积
//直接在输出中调用这个返回值就可以了
//Math.PI是准确的pai的值,可以调用这个
class Circle{
    double radius;
    public Circle(double radius){
        this.radius=radius;
    }
    public double area(){
        return Math.PI*this.radius*this.radius;

    }
    public double len(){//这里的this可以省略,因为形参中没有radius
        return 2*Math.PI*this.radius;
    }
}
posted @   f-52Hertz  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示