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...

  • Here's the problem that I have to solve: Write a Java program that uses a Stack...

    Here's the problem that I have to solve: Write a Java program that uses a Stack data structure to evaluate postfix expressions. Your program takes a postfix expression as an input,for example:3 42.3+ 5.25* ,from the user and calculates/display the result of the expression. What I'm having trouble is getting it to reading and calculating it as postfix Here's my code: import java.util.Scanner; public class Assignment2 {     public static void main(String[] args)     {         Scanner scan = new...

  • 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:...

  • Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list....

    Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list. This is only supposed to use THAT method, calling a normal Stack will give me a zero. I do have the conversion to postfix, but there may be error in there. But the main problem currently is the evaluation of postfix. I keep getting an error that I made for an empty stack, which I will include. For testing it is only supposed to...

  • *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...

  • This code in c evaluates a mathematical expression and checks that it is correctly balanced, then...

    This code in c evaluates a mathematical expression and checks that it is correctly balanced, then converts the expression to its postfix form (This part works). Now I need to evaluate the postfix expression with a function. I've been compiling it using dev c ++. #include #include #define SIZE 20 #include int profundidad(char expresion[]); int prec(char op1, char op2); void postfijo(char expresion[]); char funcion[SIZE]; float convierte(char car); float resultado(float opnd1, char symb, float opnd2); float evaluar(char expresion[]); #define SIZE 20...

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