设计计算器类 Calculator,计算加、减、乘、除和立方体体积,并且打包为 mypackage在 Calculator Java同一目录下新建文件 PackageDemo. Java,其中设计测试类引用计算器类的各方法显示计算结果。
Calculator.java
package mypackage;
public class Calculator {
double add(double num1,double num2)
{
return num1 + num2;
}
double minus(double num1,double num2){
return num1 - num2;
}
double multiple(double num1,double num2)
{
return num1 * num2;
}
double divide(double num1,double num2)
{
return num1 / num2;
}
double cube(double num1,double num2){
return (double) Math.pow(num1,num2);
}
}
PackageDemo.java
package mypackage;
import java.util.Scanner;
public class PackageDemo {
public static void main(String[] args) {
double ans;
Scanner scanner = new Scanner(System.in);
double num1 = scanner.nextInt();
double num2 = scanner.nextInt();
Calculator c=new Calculator();
ans=c.add(num1,num2);
System.out.println("相加:"+String.format("%.2f", ans));
ans= c.minus(num1,num2);
System.out.println("相减:"+String.format("%.2f", ans));
ans=c.multiple(num1,num2);
System.out.println("相乘:"+String.format("%.2f", ans));
ans=c.divide(num1,num2);
System.out.println("相除:"+String.format("%.2f", ans));
ans=c.cube(num1,num2);
System.out.println("乘方:"+String.format("%.2f", ans));
}
}