(OJ)Java面向对象-构造方法

构造方法

Problem Description

编写Java程序模拟简单的计算器。定义名为Number的类,其中有两个整型数据成员x和y,声明为私有。编写构造方法赋予x和y初始值,再为该类定义加add、减sub、乘mul、除div等公有成员方法分别对两个成员变量执行加、减、乘、除的运算。 在main方法中创建Number类的对象调用各个方法并显示计算结果。

// 你的代码将嵌入这里

public class Main{
   public static void main(String[] args){
       Number num=new Number(4,4);
       num.add();
       num.sub();
       num.mul();
       num.div();
    }
}

Output Description

the result is:8
the result is:0
the result is:16
the result is:1

解题代码

// Number类
class Number{
    
    
    // 成员x
    private int x;
    // 成员y
    private int y;
	
    // 带参构造
    public Number(int x, int y) {
    
    
        this.x = x;
        this.y = y;
    }
	
    // 加运算的方法
    void add(){
    
    
        int res = x + y;
        System.out.println("the result is:" + res);
    }

    // 减运算的方法
    void sub(){
    
    
        int res = x - y;
        System.out.println("the result is:" + res);
    }

    // 乘运算的方法
    void mul(){
    
    
        int res = x * y;
        System.out.println("the result is:" + res);
    }

    // 除运算的方法
    void div(){
    
    
        int res = x / y;
        System.out.println("the result is:" + res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112563291