2
\$\begingroup\$

How to optimize below code to reduce code with better performance?

import java.util.Scanner;

public class ConsoleCalculatorImproved 
{
    static boolean ERROR = true;
    public static void main(String[] m)
    {
        String arg ;
        ConsoleCalculatorImproved cC = new ConsoleCalculatorImproved();
        CalculatorMain cM = cC.new CalculatorMain();
        float result;
        Scanner cInput = new Scanner(System.in);
        try
        {
            arg = m[0];
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Enter Expression : ");
            arg = cInput.nextLine();
        }
        result = cM.evaluateExpression(arg);
        if(ERROR == false) 
        System.out.println(arg+" = "+result);
    }
    class CalculatorMain
    {
        String expression;
        StringBuilder numExtractor;
        float result,temp;
        int opCount;
        char operator,current;
        public CalculatorMain()
        {
            expression = new String();
            numExtractor = new StringBuilder();
            numExtractor.setLength(10);
            opCount =  0;
            result = temp = 0;
            operator = current = 0;
        }
        public boolean isDigit(char test)
        {
            if(test >='0' && test <='9') return true;
            else return false;
        }
        public float evaluateExpression(String exp)
        {
            expression = exp.trim();
            expression = "("+expression+")";
            int i,sc=0;
            for(i=1;i<expression.length();i++)
            {
                current = expression.charAt(i);
                if(i == 1)
                {
                    if(isDigit(current)||current=='-')
                        numExtractor.setCharAt( sc++ , current );
                    else if(current == '(')
                    {
                        if(expression.indexOf(')') != expression.lastIndexOf(')'))
                        {
                            CalculatorMain cm = new CalculatorMain();
                            String Temporary = expression.substring(2,expression.indexOf(')'));
                            result = cm.evaluateExpression(Temporary);
                            i = expression.indexOf(')');
                            StringBuilder t = new StringBuilder(expression);
                            t.setCharAt(expression.indexOf(')'),'x');
                            expression = t.toString();
                        }
                        else
                        {
                            System.out.println("ERROR : Pair of Brackets Expected");
                        }
                    }
                    else
                    {
                        System.out.println("ERROR : Invalid Expression !");
                        return result;
                    }
                }
                else if( ( expression.charAt(i-1) != 'x' ) && ( current == ')' ))
                {
                    if(opCount == 0)
                    {
                        result = Float.parseFloat(numExtractor.toString());
                        break;
                    }
                    else
                    {
                        temp = Float.parseFloat(numExtractor.toString().trim());
                        switch(operator)
                        {
                            case'+': result+=temp;break;
                            case'-': result-=temp;break;
                            case'*': result*=temp;break;
                            case'/': result/=temp;break;
                        }
                        break;
                    }
                }
                else if( ( expression.charAt(i-1) == 'x' ) && ( current == ')' ))
                {
                    break;
                }
                else
                {
                    if(isDigit(current) || (current == '.') )
                    {
                        numExtractor.setCharAt( sc++ , current);
                    }
                    else if(current == '-' && ( expression.charAt(i-1) == '+' || expression.charAt(i-1) == '-' || expression.charAt(i-1) == '*' || expression.charAt(i-1) == '/' ))
                    {
                        numExtractor.setCharAt( sc++ , current);
                    }
                    else
                    {
                        if((expression.charAt(i-1)!='x')&&(current == '+' || current == '-' || current == '*' || current == '/'))
                        {   
                            if(opCount==0)
                            {
                                result = Float.parseFloat(numExtractor.toString().trim());
                                numExtractor = new StringBuilder();
                                numExtractor.setLength(10);
                                sc = 0;
                                opCount++;
                                operator = current;
                            }
                            else
                            {
                                temp = Float.parseFloat(numExtractor.toString().trim());
                                numExtractor = new StringBuilder();
                                numExtractor.setLength(10);
                                sc = 0;
                                switch(operator)
                                {
                                    case'+': result+=temp;break;
                                    case'-': result-=temp;break;
                                    case'*': result*=temp;break;
                                    case'/': result/=temp;break;
                                }
                                operator = current;
                                temp = 0;
                                opCount++;
                            }
                        }
                        else if((expression.charAt(i-1)=='x')&&(current == '+' || current == '-' || current == '*' || current == '/'))
                        {
                            opCount++;
                            operator = current;
                        }
                        else if(current == '(')
                        {
                            if( opCount !=0 && (expression.indexOf(')') != expression.lastIndexOf(')')))
                            {
                                CalculatorMain cm = new CalculatorMain();
                                String Temporary = expression.substring(i+1,expression.indexOf(')'));
                                temp = cm.evaluateExpression(Temporary);
                                i = expression.indexOf(')');
                                StringBuilder t = new StringBuilder(expression);
                                t.setCharAt(expression.indexOf(')'),'x');
                                expression = t.toString();
                                switch(operator)
                                {
                                    case'+': result+=temp;break;
                                    case'-': result-=temp;break;
                                    case'*': result*=temp;break;
                                    case'/': result/=temp;break;
                                }
                            }
                            else if(opCount == 0)
                            {
                                System.out.println("ERROR : Missing Operator before Bracket");
                                return result;
                            }
                            else
                            {
                                System.out.println("ERROR : Pair of Brackets Expected");
                            }
                        }
                        else
                        {
                            System.out.println("Invalid Expression!");
                            return result;
                        }
                    }
                }
            }
            ERROR = false;
            return result;
        }
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Maybe you should tell us what this code does, how it works and why it works the way it works? \$\endgroup\$
    – Bobby
    Commented Jun 3, 2013 at 11:15

3 Answers 3

1
\$\begingroup\$

You need to compile and interpret a programming language, even though your language is rather simple expression language. Write recursive descent parser or use ANTLR.

\$\endgroup\$
1
\$\begingroup\$

You should consider using Parboiled. It allows you to write grammars entirely in Java.

As a bonus, it has a calculator example, complete with parens etc.

I know ANTLR is generally the name that comes first; but the fact that Parboiled does not require that you "precompile" your grammars is a HUGE bonus.

\$\endgroup\$
0
\$\begingroup\$

You should read about the Shunting-yard algorithm. It can be used to parse mathematical expressions in the normal (infix) notation into postfix notation (or Reverse Polish Notation), which can then be evaluated easily (and efficiently).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.