I have a weird problem in java. I am trying to make a math expression calculator which would evaluate an infix math expression and return the final result on the screen. I have used stacks to accomplish the task and so far, I was using a hardcoded string for input, but then I changed it to command line arguments for the same purpose. My problem is that, the stacks which I am using just won't push values into themselves from the commandline inputs although the datatype and the strings are exactly the same.
Here is the code to push data into the stack.
public class Expression
{
public static void main(String argv[]){
Stack<String> operator = new Stack<String>();
Stack<String> operand = new Stack<String>();
/*
String push[] = new String[argv.length];
for (int i = 0; i<push.length; i++){
push[i] = argv[i];
}
*/
for(int i = 0; i<argv.length; i++){
if(argv[i] == "+" || argv[i] == "-" || argv[i] == "*"
|| argv[i] == "/" || argv[i] == "^") {
operator.push(argv[i]);
} else if(argv[i] == "0" || argv[i] == "1" || argv[i] == "2"
|| argv[i] == "3" || argv[i] == "4" || argv[i] == "5"
|| argv[i] == "6" || argv[i] == "7" || argv[i] == "8"
|| argv[i] == "9") {
operand.push(argv[i]);
}
}
System.out.println(operand);
System.out.println(operator);
Stack<String> result = evaluateStack(operand, operator);
System.out.println(result.toString());
}
}
When I used the debugger using harcoded string, it was showing that the stack was filled normally, but with commandline arguments, it always shows the stacks with 0 elements even when the for loop is completed. What am I doing wrong?
Be sure when to use "==" and when to use "equals"....
"==" will be used to check the equality of the String objects
and
"equals(...)" will be used to the check the content of the String objects.
your problem will be solved when you use the equals(...) method for checking the operands
operators