The Artima Developer Community
Sponsored Link

Java Answers Forum
Reverse polish using a tokenizer

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
robert

Posts: 1
Nickname: kopyo
Registered: Jun, 2003

Reverse polish using a tokenizer Posted: Jun 30, 2003 7:09 AM
Reply to this message Reply
Advertisement
I have been stuck on this for several days now.
I am trying to create a reverse polish calculator and I'm stuck at an intermediate stage.
This is what I know i have to do (just not sure how to do it to much of a newbie :( )
I'm trying to call method, isOp, in the int method, evaluate. While in INT evaluate method and in a while(hasNextToken) loop. Calling isOp on each token, nextToken.

If it returns False, convert to (Integer) and push the token into a Stack. True, you will pop the two tokens, convert them to (Integer) and store them into x and y respectively. Do the Arithmetic operation and then push it back to the stack.

I'm pretty sure the IsOp test is good just can't figure out the first part.


I am trying to get the following code to work:
public class Evaluator {//tokList contains a list of tokens in postfix notation.
//evaluate the expression and return the result
int x, y,resu;
int i,j=0;
public int evaluate (ArrayList tokList) {
while (tokList.hasNextToken()){
isOp (s);
(tokList.nextToken());

Stack eval =new Stack();

if (false)
eval.push(new Integer(s));
else
{ y=((Integer) eval.pop()).intValue();
x=((Integer) eval.pop()).intValue();
switch (s)
{
case '+':
resu=x+y;
break;
case '-':
resu=x-y;
break;
case '*':
resu=x*y;
break;
case '/':
resu=x/y;
break;
default:
resu=0;
}
eval.push(new Integer(resu));

}
}
resu= ((Integer) eval.pop()).intValue();
return resu;
}
}

// Check whether s represents an operator
private boolean isOp(String s) {
return( s.equals( " + " ) || s.equals( " -- " ) || s.equals( " / " ) || s.equals( " * " ) );
// implement proper code here
} //isOp


private boolean hprecedence(String a, String b) {
return !a.equals("(") && (b.equals("+") || b.equals("-")
|| a.equals("*") || a.equals("/"));
} //precedence

}



Any help would be greatly appreciated, I'm told it's quite simple once you know how but i don't know....

Topic: tricky problem with a code Previous Topic   Next Topic Topic: how to learn java in 2 days

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use