Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- import java.util.StringTokenizer;
- public class Parser{
- /*
- * This class offers methods to handle the calculators input stream
- * strings. The constructor is to tokenize the stream and the method
- * is to convert it to reverse polish notation.
- */
- StringTokenizer st;
- public Parser(String input){
- /*
- * The possible tokens are the operators and numbers. All other
- * character is dropped out, assuming them being typos.
- */
- st = new StringTokenizer(input, Operator.getOperatorString()+"()", true); //The delimiters are the operators and the brackets. They must be in the token stream also.
- }
- public String[] convertToRPN(){
- /*
- * Turning the tokenized stream into a reverse polish notationed
- * array of strings using the shunting-yard algorithm.
- */
- Stack<String> opStack = new Stack<String>();
- String[] rpn = new String[st.countTokens()];
- boolean wasOperator = true;
- int index = 0;
- while( st.hasMoreTokens() ){
- String temporary = st.nextToken();
- if( temporary.equals("(")){ //The brackets are unneeded, but for the negative numbers the opening side is works as an operator.
- opStack.push(temporary);
- wasOperator = true;
- } else if( (temporary.equals("-") ) && (wasOperator)){ //This is it. When the previous token was an operator, the "-" is just signs a negative number.
- //Yet the possibilitiy of too much minuses aren't examined.
- rpn[index] = Double.toString( -1 * Double.parseDouble(st.nextToken()) );
- index++;
- } else if( temporary.equals(")")){ //The closing bracket means we have to empty the operators stack.
- while( !(opStack.peek().equals("(")) ){
- rpn[index] = opStack.pop();
- index++;
- wasOperator = false; //And, of course this means that the next tokan must be an operator.
- }
- opStack.pop();
- }else if( Operator.isOperator(temporary) ){ //Here we push the operators to the stack, until they have a lower precedence than the actual.
- while( ( !(opStack.empty()) ) && ( !(opStack.peek().equals("(")) ) && (Operator.getPrecedence(opStack.peek()).byteValue() > Operator.getPrecedence(temporary).byteValue() ) ){
- rpn[index] = opStack.pop();
- index++;
- }
- opStack.push(temporary);
- wasOperator = true;
- } else {
- rpn[index] = temporary;
- index++;
- wasOperator = false;
- }
- }
- while( !(opStack.empty()) ){ //We need emptying the stack. Just popping everything out from it.
- rpn[index] = opStack.pop();
- index++;
- }
- return rpn;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement