private String formatString ( String exp ) { exp = exp . replaceAll ( "\\s" , "" ) ; // why exp = exp . toLowerCase ( ) ; int count = 0 ; if ( exp . substring ( 0 , 1 ) . equals ( "-" ) ) { // if expression starts with a minus sign, it is a unary one exp = "$" + exp . substring ( 1 ) ; // replace } for ( int i = 0 ; i < exp . length ( ) ; i ++ ) { if ( exp . substring ( i , i + 1 ) . equals ( "(" ) ) count ++ ; else if ( exp . substring ( i , i + 1 ) . equals ( ")" ) ) count -- ; } while ( count > 0 ) { exp += ")" ; count -- ; } // At the operators, when the operator is "-" and it is preceded by another operator, // or preceded by a left parenthesis, or when it is the first character of the input // it is a unary minus rather than binary. In this case, I change it to another // character, '$', and make its precedence the same as that of '^'. for ( int i = 0 ; i < exp . length ( ) - 1 ; i ++ ) { String tmp1 = exp . substring ( i , i + 1 ) ; String tmp2 = exp . substring ( i + 1 , i + 2 ) ; if ( tmp2 . equals ( "-" ) && ( ExpressionParser . isOperator ( tmp1 ) || tmp1 . equals ( "(" ) ) ) exp = exp . substring ( 0 , i + 1 ) + "$" + exp . substring ( i + 2 ) ; else if ( ( tmp1 . matches ( "[0-9]+" ) || tmp1 . equals ( var ) ) && ( tmp2 . equals ( "(" ) || tmp2 . equals ( var ) ) ) exp = exp . substring ( 0 , i + 1 ) + "*" + exp . substring ( i + 1 ) ; } return exp ; }
adds and deletes characters to aid in the creation of the binary expression tree