题目:用java实现一个简单的计算器功能(用户从控制台输入)计算两个数和一个运算符号
public class Optioner { private int numFirst; private int numSecond; public int getNumFirst() { return numFirst; } public void setNumFirst(int numFirst) { this.numFirst = numFirst; } public int getNumSecond() { return numSecond; } public void setNumSecond(int numSecond) { this.numSecond = numSecond; } public Optioner() { } public Optioner(int numFirst, int numSecond) { this.numFirst = numFirst; this.numSecond = numSecond; } public int getResult() { return 0; } }
public class AddOptioner extends Optioner { @Override public int getResult() { return getNumFirst() + getNumSecond(); } } public class SubOptioner extends Optioner { @Override public int getResult() { return getNumFirst() - getNumSecond(); } } public class MulOptioner extends Optioner { @Override public int getResult() { return getNumFirst() * getNumSecond(); } } public class DivOptioner extends Optioner { @Override public int getResult() { if (getNumSecond() == 0) { System.out.println("除数不能为0"); return -1; } else { return getNumFirst() / getNumSecond(); } } }
public class OptionerFactory { public static Optioner createOptioner(String opt) { Optioner optioner = null; switch (opt) { case "+": optioner = new AddOptioner(); break; case "-": optioner = new SubOptioner(); break; case "*": optioner = new MulOptioner(); break; case "/": optioner = new DivOptioner(); break; } return optioner; } }
public class Test { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.print("请输入第一个数:"); int numFirst = scanner.nextInt(); System.out.print("请输入操作方式(+,-,*,/):"); String opt = scanner.next(); System.out.print("请输入第二个数:"); int numSecond = scanner.nextInt(); Optioner optioner = OptionerFactory.createOptioner(opt); optioner.setNumFirst(numFirst); optioner.setNumSecond(numSecond); System.out.println("结果为:" + optioner.getResult()); } }
Optioner是父类,根据情况不同,通过OptionerFactory工厂得到对应的实际操作类
Optioner封装了两个参数和操作符,加减乘除类继承了Optioner,OptionerFactory中多态得到了对应的加减乘除类。
加减乘除独自成类是为了拓展更多的操作运算,然后只要在工厂类中加判断条件即可,其他类不用动