复数C.

时间:2017-05-21 12:44:52

标签: java

下面我有我的代码用于创建复杂的数字,我可以调用加法或减法或除以对象而无需对其进行硬编码,我该怎么做呢?

  Scanner firstguess = new Scanner(System.in);
  System.out.println("Please enter the real part:  ");
  double first = firstguess.nextDouble();

  Scanner secon = new Scanner(System.in);
  System.out.println("Please enter the imaginary part:  ");
  double second = secon.nextDouble();

  Complex a = new Complex(num, denom);
  Complex b = new Complex(first, second);
  Scanner g = new Scanner(System.in);
  System.out.println("Please enter the arithmetic you want done:  ");
  String choice = g.next();

  System.out.println(a.add(b));

1 个答案:

答案 0 :(得分:0)

  

我想知道如何调用它们而不必硬编码我选择的方法 - Daniel

基本上你无法避免这种情况。不知怎的,你必须告诉电脑该做什么......

更好的问题是:如何选择正确的方法进行调用。

你有一些选择:

  • if / else cascade
  • 开关
  • 通用界面和地图

由于只有最后一个是朝向OOP(而其他人是程序方法,我将证明:

您可以定义自定义界面

interface ComplexOperation{
 Complex calculate(Complex c1, complex c2);
}

您可以像这样定义地图

Map<String,ComplexOperation> operations = new HashMap<>();

然后将操作符号与接口的实现一起放在该映射中:

operations.put("+",new AddOperation()); // form 1: top level or named inner class
operations.put("-",new ComplexOperation() { // form 2: anonymous inner class 
    @Override
    public Complex calculate(Complex c1, complex c2){
      return c1.subtract(c2);
    }
});
operations.put("*",(c1,c2) -> c1.multiply(c2)); // form 3: Java8 Lambda.

表格1需要额外的课程:

class AddOperation implements ComplexOperation{
    @Override
    public Complex calculate(Complex c1, complex c2){
      return c1.add(c2);
    }
}    

你这样使用它:

 System.out.println("Please enter the arithmetic you want done:  ");
  String choice = g.next();

  if(operations.containsKey(choice)){
    System.out.println(operations.get(choice).calculate(c1,c2));
  else
    System.err.println("invalid operation: "+choice);