Question

In: Computer Science

Please construct a code following the instructions below Part 3 – infixEvaluator method You are required...

Please construct a code following the instructions below

Part 3 – infixEvaluator method

You are required to implement the following method:  

public static double infixEvaluator(String line)

This function first needs to tokenize the input expression (in the form of a String and stored in input variable “line”). You can tokenize the input expression by creating an object of StringSplitter and passing it the String as follows. StringSplitter uses a queue to accomplish the tokenization (see the class for details).

StringSplitter data = new StringSplitter(line);

Next, create your two stacks. Remember one will contain the operators and the other one will include the operands. Define them as follows:

Stack<String> operators = new Stack<String>();  

Stack<Double> operands = new Stack<Double>();

Before we continue further in this method, it will be helpful to consider helper methods we might need (which will make our job easier :-).

Skeleton of the code below:

/**

* give a description of the purpose of this method

* @param line fill in

* @return fill in

*/

public static double infixEvaluator(String line){

return 0.0; // placeholder

}

Solutions

Expert Solution

Hello There,

Code for the above probem is given as :-

import java.util.Stack;

    public static double infixEvaluator(String line)

    {

        char[] tokenized = line.toCharArray();

         // to store operands..

        Stack<Double> operands = new Stack<Double>();

        // to store operators..

  Stack<Character> operators = new Stack<Character>();//taking of Character type as it is converted to character array above..

        for (int i = 0; i < tokenized.length; i++)

        {

             // if a current character is a whitespace just skip..

if (tokenized[i] == ' ')

                continue;

            // if a current character is a number just push it to stack of operators..

            if (tokenized[i] >= '0' && tokenized[i] <= '9')

            {

                StringBuffer S_B = new StringBuffer();

                // it is possible that it contains more than single digit numbers..

                while (i < tokenized.length && tokenized[i] >= '0' && tokenized[i] <= '9')

S_B.append(tokenized[i]);

i=i+1;

operators.push(Double.parseDouble(S_B.toString())); //converting each character to Double because calculations done in Double values..

            }

            // if an opening bracket is encountered push it to operands...

            else if (tokenized[i] == '(')

                operands.push(tokenized[i]);

            // For a closing bracket the whole brace is needed to be solved..

            else if (tokenized[i] == ')')

            {

                while (operands.peek() != '(')

operators.push(helper(operands.pop(), operators.pop(), operators.pop()));

                operands.pop();

            }

            // for operators we have : -

        else if (tokenized[i] == '+' || tokenized[i] == '-' || tokenized[i] == '*' || tokenized[i] == '/')

            {

                // Now until top of operands has same or greater precedence than current

                // character that is operator. Solve top two of operators as according to

                // top of operands ..

             while ( check_precedence(tokenized[i], operands.peek()) && !operands.empty() )

operators.push(helper(operands.pop(), operators.pop(), operators.pop()));

                // Push current character to operands...

                operands.push(tokenized[i]);

            }

        }

        // After parsing till here apply the available operands to remaining operators...

        while (!operands.empty())

operators.push(helper(operands.pop(), operators.pop(), operators.pop()));

// return the top of operators as an final answer...

        return operators.pop();

    }

    // this check_precedence function gives true if operand_2 has higher or same precedence as of operand_1 ,..

    // otherwise it simply returns false.

    public static boolean check_precedence(char op1, char op2)

    {  

  

if ((operand_1 == '/' || operand_1 == '*') && (operand_2 == '+' || operand_2 == '-'))

            return false;

         if (operand_2 == '(' || operand_2 == ')')

            return false;

        else

            return true;

    }

    // an helper function to calculate result of top two operators..

    public static Double helper(char operand, Double x, Double y)

    {

if(operand=='*')

return x * y;

else if(operand=='+')

            return x + y;

else if(operand=='-')

            return x - y;

else if(operand=='/')

{

  if (y == 0)

{

throw new

UnsupportedOperationException("divide by zero exception occur..");

}

            return a / b;

        }

        return 0.0; //placeholder

    }

This is the required code to solve the infix experession using two stacks...for any further doubt you can ask again...

Thanks for reaching out to us..

keep asking and keep learning... :)))))


Related Solutions

Please complete the following code in C using the comments as instructions. Further instructions are below...
Please complete the following code in C using the comments as instructions. Further instructions are below the code. challenge.c // goal: print the environment variables to the file "env.txt", one per line // (If envp is NULL, the file should be empty, opening in write mode will do that.) // example: // inputs: // envp/environ = {"E1=2","E2=7",NULL} // outputs: // env.txt as a string would be "E1=2\nE2=7\n" // example: // inputs: // envp/environ = {NULL} or NULL // outputs: //...
Please code by C++ The required week2.cpp file code is below Please ask if you have...
Please code by C++ The required week2.cpp file code is below Please ask if you have any questions instruction: 1. Implement the assignment operator: operator=(Vehicle &) This should make the numWheels and numDoors equal to those of the object that are being passed in. It is similar to a copy constructor, only now you are not initializing memory. Don’t forget that the return type of the function should be Vehicle& so that you can write something like: veh1 = veh2...
Please answer part a) through part d) of the question below. Thank you. Question 3 A...
Please answer part a) through part d) of the question below. Thank you. Question 3 A tobacco refinery has four methods of measuring pH. To test the four methods, a supervisor randomly assigns each of 32 tobacco samples with known pH to one of the four methods, so that each method is applied to exactly eight samples. The difference between measured pH and the known pH is recorded, and the data is below. Method Sample Response A 1 -0.307 A...
[50%] Code Snippet Given snippet code below that you are required to complete. You are not...
[50%] Code Snippet Given snippet code below that you are required to complete. You are not allowed to make a new function or change any given code. Please complete each section that are marked with the notation “INSERT YOUR CODE HERE”. Once you complete the snippet below, your output should have the same result with the given output below. Descriptions: [15%] isValid() This function is for checking that there is no duplicated employee data in the linked list. This function...
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite...
PART A - STACKS To complete this assignment: Please study the code posted below. Please rewrite the code implementing a template class using a linked list instead of an array. Note: The functionality should remain the same *************************************************************************************************************** /** * Stack implementation using array in C/procedural language. */ #include <iostream> #include <cstdio> #include <cstdlib> //#include <climits> // For INT_MIN #define SIZE 100 using namespace std; /// Create a stack with capacity of 100 elements int stack[SIZE]; /// Initially stack is...
1. Please program the following in Python 3 code. 2. Please share your code. 3. Please...
1. Please program the following in Python 3 code. 2. Please share your code. 3. Please show all outputs. Instructions: Run Python code  List as Stack  and verify the following calculations; submit screen shots in a single file. Postfix Expression                Result 4 5 7 2 + - * = -16 3 4 + 2  * 7 / = 2 5 7 + 6 2 -  * = 48 4 2 3 5 1 - + * + = 18   List as Stack Code: """...
Project Instructions Please read the following instructions and review the table below carefully. Then, enter answers...
Project Instructions Please read the following instructions and review the table below carefully. Then, enter answers for journal items [A] to [V] in the next item in this lesson, called Project 1 Part 1 Journal Entries for Accrual Accounting. You may keep these instructions open in a separate browser or download the instructions as a PDF, and open it as you work through the exercise. Illini Company, Inc. Balance Sheet as of 12/31/20X0 Assets Current Assets: Cash 1,500,000 Accounts receivable,...
Please complete the following code in challenge.c. The code for main.c and challenge.h is below that....
Please complete the following code in challenge.c. The code for main.c and challenge.h is below that. (Don't edit main.c or challenge.h, only edit challenge.c) The instructions are in the comments. Hint: the_person is declared in main, so you need to define it in challenge.c using extern challenge.c #include "challenge.h" //return: struct //param: (struct person p1, struct person p2) //TODO: create a function that returns the person who has a higher GPA. // 1. if GPAs are equal, then return the...
C programming assignment. instructions are given below and please edit this code only. also include screenshot...
C programming assignment. instructions are given below and please edit this code only. also include screenshot of the output //In this assignment, we write code to convert decimal integers into hexadecimal numbers //We pratice using arrays in this assignment #include <stdio.h> #include <stdlib.h> #include <assert.h> //convert the decimal integer d to hexadecimal, the result is stored in hex[] void dec_hex(int d, char hex[]) {    char digits[] ={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',   ...
Please carefully review the code to fill in after the given instructions and complete the code...
Please carefully review the code to fill in after the given instructions and complete the code for me. Thank you in advance. In this problem, we will implement a simple dictionary of common words in the English language, represented as an array of words paired with their lengths. You will need to implement each of the below methods in the Dictionary class. In this problem, the first line of input represents the method to call. It will be one of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT