Is the if-else tree the best way in the following case?

What am I doing:

I am creating a simple calculator in Java that reads a string that was written using postfix notation (ex: 3 4 +). Then he takes the line and begins to read it from left to right. It stores each number found and then applies the next statement. For example: 3 4 + → save 3, save 4, run 3 + 4 and save the result.

I need help:

How characters should be checked for predefined operators (if (c == '/'), etc.). What alternatives exist in my case for the if-else tree, and which one should I choose if I want, so that I can add new operators with minimal effort (and minimal cost for performance). What is generally considered good practice?

+3
source share
6 answers

If you encapsulate your operations as objects, you can often use the data structure to replace the operator switch, and hopefully just add operations in the future.

For example, this is one way to encapsulate operations as objects: using Enum to represent operations:

http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html

public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}

, , . [[ UI/view /, , , , , .]]

, , , :

  • , - .

  • , , , .

+5

, ( ). , if-tree .

, - Operator, , , ( "+", "-", "*", ..) .

+8

, / 1 , ( )

, , if/else switch

switch(ch) {
  case '+':

     break;
  case '-':

     break;
  // etc.
}
+5

, Command Pattern, Character , .

+4

, Operator, , ( , ).

abstract class Operator {
    String simbol;
    abstract Double calculate(Double firstOperand, Double secondOperand)
}

class Sum extends Operator {
    simbol = "+";
    Double calculate(Double firstOperand, Double secondOperand){
        return firstOperand + secondOperand;
    }    
}

class OperatorRecognizer {
    List<Operator> operators;
    public Operator recognize(String readOperator){
        for(Operator operator : operators){
            if(operator.getSymbol().equals(readOperator)){
                return operator;
            }
        }
    }
}

:

OperatorFactory.recognize(readOperator).calculate(firstOperand, secondOperand);

, , .

: lol ok, , , ^^ "

+2

. , - , . , - , .

am Enum . - , var args .

String ( ), , , ( , Postfix). , .

+1

Source: https://habr.com/ru/post/1788529/


All Articles