I am trying to write a program that evaluates a postfix expression. My idea is to stack the operands and then pop out the necessary operands when an operator occurs. I am trying to check if the input is an operand is an operator or operand, but the only "if" statement of this beginning code is returning "error: illegal start of expression" at the first instance of ||. Am I missing escape characters or something else? Thanks in advance.
public class Evaluate{
char input[] = new char[50];
Stack operands = new Stack();
public string Evaulate(string input){
for (int k = 0; input[k] != null; k++){
char symb = input.charAt[k];
if (symb != (+ || - || * || / || $){
operands.push(symb);
}
}
}
}
For a start, conditions don't quite work that way:
if (symb != (+ || - || * || / || $) ...
What you should be doing is first comparing them with characters rather than "naked" Java tokens (or $
).
You should also be doing full comparisons between each ||
or, since you're using negative logic here to detect non-operators, &&
:
if ((symb != '+') && (symb != '-') && ...
There are a few other problems in your code which I haven't mentioned but that should fix your immediate problem.
The expression
symb != (+ || - || * || / || $
is not valid in Java. Even after closing the parentheses and quoting the symbols, like this:
symb != ('+' || '-' || '*' || '/' || '$')
it is still not valid. You may want it to mean something that it does not, based on the way we can use "or" in English (ie, "symbol is not a plus or a minus or a star or a slash or a dollar sign"). But Java just doesn't do things that way.
Fortunately there is a better way to determine whether a character (in this case symb
) is one of a certain set of characters :
if ("+-*/$".indexOf(symb) >= 0) {
This computes the position of symb
within the string "+-*/$"
which, if symb
is one of the desired characters, will be 0, 1, 2, 3, 4, or 5. If it is not, the expression returns -1. So the >=0
check serves as the membership check you are looking for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.