import java.text.DecimalFormat; import java.util.Scanner; public class Test006 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入m:"); int m = sc.nextInt(); System.out.println("输入n:"); int n = sc.nextInt(); Fun fun = new Fun(); System.out.print("加法:");fun.func(new Addition(),m,n); System.out.print("减法:");fun.func(new Subtraction(),m,n); System.out.print("乘法:");fun.func(new Multiplication(),m,n); System.out.print("除法:");fun.func(new Division(),m,n); } } interface Calculator{ Object compute(int a, int b); } /* 加法 */ class Addition implements Calculator{ @Override public Object compute(int a, int b) { return a + b; } } /* 减法 */ class Subtraction implements Calculator{ @Override public Object compute(int a, int b) { return a - b; } } /* 乘法 */ class Multiplication implements Calculator{ @Override public Object compute(int a, int b) { return a * b; } } /* 除法 */ class Division implements Calculator{ @Override public Object compute(int a, int b) { if (b != 0) { DecimalFormat df = new DecimalFormat("0.0000"); // System.out.println(df.format((float) a / b)); return (df.format((float) a / b)); } System.out.println("错误信息:分母不能为0"); return 0; } } class Fun{ public void func(Calculator calculator,int a,int b){ System.out.println(calculator.compute(a, b)); } }
java接口实现简单计算器
最新推荐文章于 2021-05-27 19:10:11 发布