Well, that doesn't respect the operator precedence, now does it?
Joined: May 19, 2001
One other way to solve this could be to do it in a more object oriented way. For example create an operator class for each logical operator (I guess only AND, OR and XOR are relevant) and make each type be responsible for calculating the result of its operation, given two operands. And create some factory class that takes an string as input and outputs an instance of the corresponding operator class. So if the input is "AND" then the output is an instance of the AndOperator class.
And then create one class that is responsible for assigning the operands to the operators. Note that when you have an expression like "a OP1 b OP2 c" this is easier said then done. I mean, which operator should the b-operand belong to? And if we say that it belongs to OP1, then what should be the "left" operand for OP2?
Well the answer to this lies in the operator precedence. AND comes before OR, so if the expression is "a AND b OR c" then the AND operator should get the operands "a" and "b". So what should the OR operator get as left operand? Well, the result of the AND operation! And if you design this cleverly you don't have to know the result of the AND operation when you assign the operands for the OR operation. I'll give you a hint: the operand fields doesn't have to be regular primitive booleans, they can actually be operators themselves.
I actually wrote something like this in school some years back, and it was quite fun.
Joined: Jan 15, 2009
Thanks a lot for your help Matthew,Rob And Jimi.
I think Matthew's approach is best suited to my current needs.But, I'll surely try out the method suggested by Jimi.