Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.Math;
- public class Operator{
- /*
- * This class just encapsulate the operators and their precedences.
- * With the number of the operands is stored here too. There is also
- * a method to check if the given string is an operator string. And
- * last, we have to return the operators string for tokenizing.
- */
- private final static String opSigns = new String("+-*/^");
- private final static Byte[] opPrecedence = {2,2,4,4,8};
- private final static Byte[] opOperands = {2,2,2,2,2};
- public static Byte getPrecedence(String sign){
- /*
- * Returns the precedence value of operator, represented by this
- * string.
- */
- return opPrecedence[opSigns.indexOf(sign)];
- }
- public static Byte getOperands(String sign){
- /*
- * Returns the number of operands of this operator, represented
- * by the given string.
- */
- return opOperands[opSigns.indexOf(sign)];
- }
- public static Boolean isOperator(String sign){
- /*
- * Returns true if the given string is an operator and false
- * otherwise.
- */
- return (opSigns.indexOf(sign) == -1) ? new Boolean(false) : new Boolean(true);
- }
- public static String getOperatorString(){
- /*
- * Just return the string containing the operators characters.
- */
- return opSigns;
- }
- public static Double doOperation(String operator, Double[] operands){
- /*
- * Here we do the calculating with those operators. This is a
- * good place to do this, because the operator signs listed here
- * too, so maybe later won't be confused when the program gets
- * widening.
- * */
- Double result;
- switch( operator.charAt(0) ){
- case '+':{
- result = new Double( operands[1].doubleValue() + operands[0].doubleValue() );
- break;
- }
- case '-':{
- result = new Double( operands[1].doubleValue() - operands[0].doubleValue() );
- break;
- }
- case '*':{
- result = new Double( operands[1].doubleValue() * operands[0].doubleValue() );
- break;
- }
- case '/':{
- result = new Double( operands[1].doubleValue() / operands[0].doubleValue() );
- break;
- }
- case '^':{
- result = new Double(Math.pow( operands[1].doubleValue(), operands[0].doubleValue()));
- break;
- }
- default:{
- result = new Double(0);
- break;
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement