2023-03-10 java 编写程序,模拟计算器。定义名为Number的类,有两个私有整型数据成员num1和num2。编写构造方法,赋予num1和num2初始值,再为该类定义加减乘除方法。

1.创建number类
package Day3shuzu;

public class Number {
    private int num1;
    private int num2;

    public Number(){}//0个参数的构造器

    public Number(int num1, int num2) {//两个参数的构造器
        this.num1 = num1;
        this.num2 = num2;
    }


    public int  add(int num1,int num2){
        //建立一个方法,你必须让他有返回值,既然有返回值,那么必须传进来的参数有数据类型
        return num1 + num2;
    }
    public int  sub(int num1,int num2){
        return num1 - num2;

    }
    public int  mul(int num1,int num2){
        return num1 * num2;
    }
    public int  div(int num1,int num2){
        if(num2 == 0){
            System.out.println("除数不能为0.");
            return 0;
        }
        return num1 / num2;
    }



    public int getNum1() {
        return num1;
    }

    public void setNum1(int num1) {
        this.num1 = num1;
    }

    public int getNum2() {
        return num2;
    }

    public void setNum2(int num2) {
        this.num2 = num2;
    }

    @Override
    public String toString() {
        return "Number{" +
                "num1=" + num1 +
                ", num2=" + num2 +
                '}';
    }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2.在main方法中创建Number类的对象,调用各个方法,并显示计算结果。

package Day3shuzu;

import java.util.Scanner;

public class NumberDemo {
    public static void main(String[] args) {
        Number number01 = new Number();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入num1和num2:");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();
        System.out.println(number01.add(num1,num2));
        System.out.println(number01.sub(num1,num2));
        System.out.println(number01.mul(num1,num2));
        System.out.println(number01.div(num1,num2));
    }
}

你可能感兴趣的:(java,开发语言)