if的更短解决方案,否则if,否则if

时间:2013-05-23 01:11:38

标签: java parsing math if-statement int

我正在寻找缩短此代码的方法,避免重复代码和if语句。我正在做的是创建一个计算器,在字符串中搜索运算符“* / + - ”并相应地执行它们。有什么想法吗?

if(exp.charAt(i)=='*')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) * Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 
        else if(exp.charAt(i)=='/')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) / Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 
        else if(exp.charAt(i)=='+')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) + Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 
        else if(exp.charAt(i)=='-')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) - Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 

此外,是否有接受具有2个以上操作数的字符串的解决方案?即5 + 10 * 2/3

6 个答案:

答案 0 :(得分:10)

要更改代码,您可以使用switch语句并在切换之前或之后放置一些冗余代码。

int left = Integer.parseInt(exp.substring(0,i));
int right = Integer.parseInt(exp.substring(i+1,exp.length()));
switch(exp.charAt(i)){
    case '*':
        primeResult = left * right;
        break;
    case '/':
        ...
        break;
    case '+':
        ...
        break;
    case '-':
        ...
        break;
    default:
        ... // Error Handling.
}
System.out.println(primeResult);

答案 1 :(得分:6)

不需要switch语句和复杂的课程。

为了简化和缩短代码并计算简单和复杂的表达式(表示为String个对象),您可以使用Java JavaScript API及其ScriptEngine {{ 1}} class,它基本上模拟JavaScript控制台。

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class MyClass{
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        System.out.println(engine.eval("(5+10)*2/3"));
    }
}

这将输出:10.0

答案 2 :(得分:4)

您可以使用AbstractCalculationOperation方法撰写execute课程,AddSubtract等等。

然后,只需解析leftHandrightHandcalculationOperation并运行calculationOperation.execute( rightHand, leftHand )

    public interface CalculationOperation {
        double calculate ( double lh, double rh );
        long calculate ( long lh, long rh );
    }

    public class Add implements CalculationOperation {
        public static final CalculationOperation INSTANCE = new Add();
        public double calculate ( double rh, double lh ) { return lh + rh; }
        public long calculate ( long rh, long lh ) { return lh + rh; }
    }

然后:

    int lh = exp.substring(0, i);
    int rh = exp.substring(i+1);
    CalculationOperation op;
    switch( exp.charAt(i) ) {
        case '*': op = Multiply.INSTANCE; break;
        case '/': op = Divide.INSTANCE; break;
        case '+': op = Add.INSTANCE; break;
        case '-': op = Subtract.INSTANCE; break;
    }
    newResult = op.calculate( rh, lh );
    primeResult = newResult;
    System.out.println(primeResult);

备用枚举变体:

   public enum Calculation {
      ADD('+') {
         public int calculate( int lhs, int rhs ) { return lhs + rhs; }
         public long calculate( long lhs, long rhs ) { return lhs + rhs; }
         public float calculate( float lhs, float rhs ) { return lhs + rhs; }
         public double calculate( double lhs, double rhs ) { return lhs + rhs; }
      },
      SUBTRACT('-') {
         public int calculate( int lhs, int rhs ) { return lhs - rhs; }
         public long calculate( long lhs, long rhs ) { return lhs - rhs; }
         public float calculate( float lhs, float rhs ) { return lhs - rhs; }
         public double calculate( double lhs, double rhs ) { return lhs - rhs; }
      },
      MULTIPLY('*') {
         public int calculate( int lhs, int rhs ) { return lhs * rhs; }
         public long calculate( long lhs, long rhs ) { return lhs * rhs; }
         public float calculate( float lhs, float rhs ) { return lhs * rhs; }
         public double calculate( double lhs, double rhs ) { return lhs * rhs; }
      },
      DIVIDE('/') {
         public int calculate( int lhs, int rhs ) { return lhs / rhs; }
         public long calculate( long lhs, long rhs ) { return lhs / rhs; }
         public float calculate( float lhs, float rhs ) { return lhs / rhs; }
         public double calculate( double lhs, double rhs ) { return lhs / rhs; }
      };

      private final char textValue;
      Calculation ( char textValue )
      {
         this.textValue = textValue;
      }

      public abstract int calculate ( int lht, int rhs );
      public abstract long calculate ( long lht, long rhs );
      public abstract float calculate ( float lht, float rhs );
      public abstract double calculate ( double lht, double rhs );

      public static Calculation fromTextValue( char textValue ) {
         for( Calculation op : values() )
            if( op.textValue == textValue )
               return op;
         throw new IllegalArgumentException( "Unknown operation: " + textValue );
      }
   }

然后:

    int lh = exp.substring(0, i);
    int rh = exp.substring(i+1);
    Calculation op = Calculation.fromTextValue( exp.substring(i,1) );
    newResult = op.calculate( lh, rh );
    primeResult = newResult;
    System.out.println(primeResult);

答案 3 :(得分:0)

通过单独执行操作来获取变量来缩短代码。这不会减少您的“if”语句,但会大幅减少行数。

在你理解树木之前不要做多个变量......我从来没有亲自与他们合作,但我认为“表达树”是你将要追求的。 (注意:我刚刚查看谷歌,是的,表达树)

答案 4 :(得分:0)

如何避免过多的代码重复非常简单:

Integer op1= Integer.parseInt(exp.substring(0, i);
Integer op2=Integer.parseInt(exp.substring(i+1, exp.length()));
if(exp.charAt(i)=='*')  {
            newResult=op1 * op2;
} else 
....
primeResult = newResult;
System.out.println(primeResult);

但是要使用任意嵌套级别做一些更通用,更健壮和更有用的东西,你应该使用一些真正的解析器。 For example.

答案 5 :(得分:0)

这是一个片段:

public static void main(String[] args) {

        float primeResult;
        String exp = "4-2";
        int i = 1;
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        char[] myVar = new char[] { '*', '/', '-', '+' };

        for (int myVarCtr = 0; myVarCtr < myVar.length; myVarCtr++) {

            if (exp.charAt(i) == myVar[myVarCtr]) {

                try {
                    primeResult = Float.parseFloat(engine.eval(
                            (Integer.parseInt(exp.substring(0, i)))
                                    + Character.toString(myVar[myVarCtr])
                                    + (Integer.parseInt(exp.substring(i + 1,
                                            exp.length())))).toString());
                    System.out.println(primeResult);
                } catch (ScriptException e) {
                    e.printStackTrace();
                }

            }

        }
    }