编写一个类Calculator,有两个属性num1,num2,这两个数据的值,不能在定义的同时初始化,最后实现加减乘 除四种运算.
package gyy;
import java.util.Scanner;
public class Calculator {
public double num1;
public double num2;
public static void main(String[] args) {
Calculator calculator = new Calculator();
Scanner sc = new Scanner(System.in);
System.out.println("请输入两个数字:");
calculator.num1 = sc.nextDouble();
calculator.num2 = sc.nextDouble();
calculator.add();;
calculator.sub();
calculator.mul();
calculator.div();
sc.close();
}
public void add () {
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
}
public void sub() {
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
}
public void mul() {
System.out.println(num1 + " * " + num2 + " = " + (num1 * num2));
}
public void div() {
double num1 = this.num1;
double num2 = this.num2;
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
}
}
运行结果:
请输入两个数字:
9.9
1.9
9.9 + 1.9 = 11.8
9.9 - 1.9 = 8.0
9.9 * 1.9 = 18.81
9.9 / 1.9 = 5.210526315789474