Heloo. I am trying to implement a java code that will return me true or false depending on my imput. For example if i have true AND NOT( false AND true) AND NOT TRUE it should return FALSE
I tried to parse my imput String and to reorder the elements into the polish notation first then, evaluate the polish form. If i don't have NOT anywere, it works perfectly
But if i have true AND NOT( (false or false) AND (true OR false)) AND NOT TRUE it returns TRUE but it should return false.
after i run the getPolishForm() function, my RPF looks like this
true false false OR true false OR AND true NOT AND NOT AND
I see that the problem is on the second NOT because it negates all this part ( (false or false) AND (true OR false)) AND NOT TRUE but it should negate just the content in the paranthesys.
This is the function that returns a list of strings in the polsih form
ArrayList<String> getPolishForm() {
ArrayList<String> postFix = new ArrayList<String>();
if (infixForm == null)
return null;
Stack<String> stack = new Stack<String>();
for (int i = 0; i < infixForm.size(); i++) {
switch (new Priority(infixForm.get(i)).getValue()) {
case 3:
while (!stack.empty() && (stack.peek().equals("AND"))) {
postFix.add(stack.pop());
}
stack.push(infixForm.get(i));
break;
case 4:
stack.push(infixForm.get(i));
break;
case 1:
stack.push(infixForm.get(i));
break;
case 2:
while (!stack.empty() && !stack.peek().equals("LPARAN")) {
postFix.add(stack.pop());
}
stack.pop();
break;
case 5:
stack.push(infixForm.get(i));
break;
default:
postFix.add(infixForm.get(i));
break;
}
}
while (!stack.empty()) {
postFix.add(stack.pop());
}
return postFix;
}
And This is the funtion that evaluates the RPF
Boolean getResult() {
Stack<Boolean> stack = new Stack<Boolean>();
boolean result = false;
for (int i = 0; i < postFix.size(); i++) {
if (isExpression(postFix.get(i))) {
stack.push(new ReMatcher(postFix.get(i), tags).isMatch());//this line processes the string from the infixForm and returns a boolean
} else {
boolean op1 = stack.pop();
try {
boolean op2 = stack.pop();
String operator = postFix.get(i);
if (operator.equals("NOT")) {
op1 = !op1;
i++;
operator = postFix.get(i);
}
if (operator.equals("OR") )
result = op1 || op2;
} else if (operator.endsWith("AND") )
result = op1 && op2;
} catch (EmptyStackException e) {
result = !op1;
}
stack.push(result);
}
}
return stack.pop();
Thank you in advance :D