Hi,

I am working on a sort of stack calculator. If anyone can suggest a better method please advice:

Basically, using the stringtokenizer to break the string into tokens. If the token does not equal "add" or "sub" or if the token is a digit push it onto the stack... proceed to methods...

I believe that the problem is with the bolded section. I think it has something to do with the fact that I switched to using chars instead of the entire token. If the omit the bolded section and replace it with

stack.push(token);

and simply push it onto the stack it works fine; however, it does not meet my requirements. Can anyone advise on how to determine if a token is "add", "sub" or is a digit?

``````if(!token.equalsIgnoreCase("add"))
if(!token.equalsIgnoreCase("sub"))
{
[B] for(int i = 0; i < token.length(); i ++)
if(Character.isDigit(token.charAt(i)))
stack.push(token);    [/B]
}

if(token.equalsIgnoreCase("sub"))
subtract();``````

Any assistance will be appreciated.

Thanks

The stack.push is inside the for-loop. Meaning that insert the same token more than once.
For example if token="123"
then you will check if "1" is a digit and then you will push the token.
then you will check if "2" is a digit and then you will push the token.
then you will check if "3" is a digit and then you will push the token.

But if you enter token="12a". Then the first two characters will be digits and you will push to the stack the token: "12a" twice which is wrong, and then the 'a' will not be digit and you will do nothing:
1) Have a boolean inside the for-loop and if it is not a digit do something like this:
boolean isNumber=true;
for (...) {
if (char not a digit) {
isNumber = false
break;
}
}
if (isNumber) push(token)

Or better:
2)
try {
double d = Double.parseDouble(token);
stack.push(token);
} catch (NumberFormatException nfe) {
System.out.println("Token: "+token+" is not a number");
}
And you will not need the for-loop

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.