Question

I am trying to understand the following code I found in a website so that I...

I am trying to understand the following code I found in a website so that I can use it for a project that evaluates boolean expressions. The code is below but I think it is in java because I do not understand it. Can you help me describe what it is doing in c++ so that I can understand it better?

The link to the code is here: https://stackoverflow.com/questions/16762057/algorithm-to-evaluate-value-of-boolean-expression
The code is below:

public static boolean evaluateBool(String s)
{
    Stack<Object> stack = new Stack<>();
    StringBuilder expression =new StringBuilder(s);
    expression.chars().forEach(ch->
    {
        if(ch=='0') stack.push(false);  
         else if(ch=='1') stack.push(true); 
          else if(ch=='A'||ch=='R'||ch=='X')
          {
              boolean op1 = (boolean) stack.pop();
              boolean op2 = (boolean) stack.pop();
              switch(ch)
              {
                case 'A' : stack.push(op2&&op1); break;
                case 'R' : stack.push(op2||op1); break;
                case 'X' : stack.push(op2^op1); break;
              }//endSwitch  
          }else 
              if(ch=='N')
                {
                  boolean op1 = (boolean) stack.pop();
                  stack.push(!op1);
                }//endIF
    });
    return (boolean) stack.pop();
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

public static boolean evaluateBool(String s)

{

Stack<Object> stack = new Stack<>();

//NOTE: it means that we are makeing a stack which is a object type, that means it can be string, int or any other type. lets we have a stack of string i.e "TF&|!()"

T
F
&
|
!
(
)

StringBuilder expression =new StringBuilder(s);

//NOTE: this will convert the stack in string i.e now the expression will be

expression ="TF&|!()" .

expression.chars().forEach(ch->

{

if(ch=='T') stack.push(false);  

else if(ch=='F') stack.push(true);

//NOTE: this will push the T and F in stack to execute the expression like:- ! ( T | F & F )

else if(ch=='&' || ch=='|' || ch=='!' )

{

boolean op1 = (boolean) stack.pop();

boolean op2 = (boolean) stack.pop();

//NOTE: this will POP the operator like:- &, | and ! from StringBuilder expression

switch(ch)

{

case '&' : stack.push(op2&&op1); break;

case '|' : stack.push(op2||op1); break;

case '!' : stack.push(op2^op1); break;

//NOTE: Most importantly,

these will convert the operatoe into real computer operators, as of now we have these operator in char. so '&' will be converted to && expression and '|' will be || and '!' will be converted into ^(NOt operator or bit operator)

}//endSwitch  

}else

if(ch=='(' || ch==')')

{

boolean op1 = (boolean) stack.pop();

stack.push(!op1);

}//endIF

});

return (boolean) stack.pop();

//NOTE: and at last when this stack is retured it is type casted into bool, so it will be like

! ( T | F & F )

and when it is in boolen form then the result will be returned i.e false.

}

Add a comment
Know the answer?
Add Answer to:
I am trying to understand the following code I found in a website so that I...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This code in C converts infix to postfix and evaluates it. The problem is that it...

    This code in C converts infix to postfix and evaluates it. The problem is that it only evaluates one digit expressions. I need to fix it so that it can evaluate 2 digits expressions as well. #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #define SIZE 100 char s[SIZE]; int top=-1; void infixToPostfix(char *infix, char *postfix); void postfixEvaluation(char *postfix); void push(char elem){ s[++top]=elem; } char pop(){ return(s[top--]); } int pr(char elem){ // Order of precedence switch (elem) { case '(':...

  • Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...

    Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...

  • The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

    The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) {     // Check number of arguments passed     if (args.length != 1) {       System.out.println(         "Usage:...

  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • Using Java programming: Modify the delimiter class (provided below) so that it can "incorrectly" ...

    Using Java programming: Modify the delimiter class (provided below) so that it can "incorrectly" evaluate simple parenthesized math expressions . a) ask the user for the whole expression to solve b) Solve the expression only if there is no mismatch in the delimiters. If there is a mismatch, then output an error. If there is an error, allow the user to reenter a corrected/new expression. c) The program should be able to evaluate expressions that uses only the following basic...

  • Im try to create a java program that checks to see if a given boolean expression...

    Im try to create a java program that checks to see if a given boolean expression is a tautology or not my code so far is as follows: public static class TreeNode    {        char data;        TreeNode left;        TreeNode right;               TreeNode(char item)        {            data = item;            left = null;            right = null;        }    } public static...

  • I need help creating the methods for using a linked binary tree to build,evaluate, and paranthesize...

    I need help creating the methods for using a linked binary tree to build,evaluate, and paranthesize the expression. We have to use linked stack to pop and push the operands into the expression. Theres two classes: Expression: Constructor, set/gets, methods. ExpressionTest: Test driver for defining exp, and calling methods I need to put the mathematical exp (from the test class) into a binary tree, evaluate the exp in the binary tree, paranthesize it and print it out. So i need...

  • I'm getting errors that i can't figure out. I need help fixing them. particularly focus on...

    I'm getting errors that i can't figure out. I need help fixing them. particularly focus on the errors they are highlighted in bold on the list code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include "stack.h" #include "booleanEvaluation.h" #include "booleanWithError.h" /* evaluatePostfix * input: a postfix expression * output: T, F, or E * * Uses a stack to evaluates the postfix expression and returns the result as a string where "T" denotes true and "F" denotes...

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • Here is the code I have so far. I'm trying to figure out how to implement...

    Here is the code I have so far. I'm trying to figure out how to implement a boolean and use precedence. The 2nd expression should be 14 but it comes out as 28 so I'm definitely not understanding. #include <stack> #include <iostream> #include <string> using namespace std; // Function to find precedence of // operators. int precedence(char op) {    if (op == '+' || op == '-')        return 1;    if (op == '*' || op ==...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT