Question

In: Computer Science

Please use Java language in an easy way with comments! Thanks! Write a static method called...

Please use Java language in an easy way with comments! Thanks!

Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the expression evaluates to. The method MUST use a stack to perform the evaluation. Specifically, you should use the Stack class from the java.util package (For this problem, you must write a static "evaluate" method).

Also, in the same file, write a program that prompts the user to enter a postfix expression. Your program should evaluate the expression and output the result. Your program should call the "evaluate" method described above. Here are some examples:

     Postfix expression: 1 2 +
     Result: 3

     Postfix expression: 1 2 + 3 4 - *
     Result: -3

     Postfix expression: 3 4 5 + + 1 -
     Result: 11

Solutions

Expert Solution

The java program for your query is given below:

**********************************************************************************************************************************************

import java.util.Stack;
import java.util.Scanner;
public class Main
{
   // Method to evaluate value of a postfix expression
   static int evaluate(String exp){
         
       Stack<Integer> stack = new Stack<>(); //create a stack class object with Integer data type in it   
      
         
       for(int i=0 ; i<exp.length() ; i++){ // Scan all characters one by one
           char c = exp.charAt(i); //taking character at position i
          
          
          
           if(Character.isDigit(c)) // If the scanned character is an operand (number here),
           stack.push(c - '0'); // push it to the stack.
          
          
           // If the scanned character is an operator, pop two
           // elements from stack apply the operator
           else{
           int val1 = stack.pop(); //pop first element
               int val2 = stack.pop(); //pop second element
              
               switch(c){ //checking whether the operator is +,-,*,/   
                   case '+':
                   stack.push(val2+val1); //when + , add both elements add to stack
                   break;
                  
                   case '-':
                   stack.push(val2- val1); //when - , subtract both elements add to stack
                   break;
                  
                   case '/':   
                   stack.push(val2/val1); //when / , divide both elements add to stack
                   break;
                  
                   case '*':
                   stack.push(val2*val1); //when * , multiply both elements add to stack
                   break;
           }
           }
       }
       return stack.pop();   //pop from the stack and return
   }
  
   // Driver program to test above functions
   public static void main(String[] args)
   {
       System.out.print("Postfix Expression:"); //prompt the user for Postfix Expression
       Scanner input = new Scanner(System.in); //defining scanner class object
       String expression = input.nextLine(); //taking input of expression with scanner object
       System.out.println("Result: "+evaluate(expression)); //Print Result
   }
}

**********************************************************************************************************************************************

Providing screenshot of the code for further reference:

Output of the program :


Related Solutions

Please use Java language in an easy way with comments! Thanks! Create a calculator that uses...
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses an array of buttons for numbers from 0-9, the . for decimals, and for operators +, -, * ,/ and = as well as a JTextfield that displays the current value or the result. Use ActionListeners and LayoutManagers appropriately. The example below shows how to determine which button has been clicked. ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println(actionEvent.getActionCommand()); }...
Please use java language in an easy way and comment as much as you can! Thanks...
Please use java language in an easy way and comment as much as you can! Thanks 1. A driver class with a main method, which creates instances of various objects (two of each subclass) and adds them as items to an ArrayList named "inventory". A foreach loop should loop through the ArrayList and call the use() method of each item. Define the ArrayList in a way that it only holds elements of the GameItem class and its subclasses. Make proper...
Please use java language in an easy way and comment as much as you can! Thanks...
Please use java language in an easy way and comment as much as you can! Thanks (Write a code question) Write a generic method called "findMin" that takes an array of Comparable objects as a parameter. (Use proper syntax, so that no type checking warnings are generated by the compiler.) The method should search the array and return the index of the smallest value. (Analysis of Algorithms question) Determine the growth function and time complexity (in Big-Oh notation) of the...
Please use java language in an easy way and comment as much as you can! Thanks...
Please use java language in an easy way and comment as much as you can! Thanks (Write a code question) Write a generic method called "findMin" that takes an array of String objects as a parameter. (Use proper syntax, so that no type checking warnings are generated by the compiler.) The method should search the array and return the index of the smallest value.
Please use java language in an easy way with comments! Expand your below program, so it...
Please use java language in an easy way with comments! Expand your below program, so it can include cursed items (weapons that break, armor that causes more damage when worn). In order to do that, write an interface called "CursedItem". Then create subclasses of the armor, and weapon class that implement the CursedItem interface : CursedWeapon: using a random number generator, there is a 4 in 10 chance that the weapon breaks during combat. CursedArmor: this item amplifies the damage...
Please use Java language with comments! Thanks! Write a program that will display multiple dots move...
Please use Java language with comments! Thanks! Write a program that will display multiple dots move across the Frame and randomly change direction when they hit the edge of the screen. Do this by creating a Dot class and making each dot an object of that class. You may reuse code written in class for this part of the assignment. Create a subclass of the Dot class called PlayerDot that is controlled by the player through keyboard input (arrow keys)...
Please use Java language! With as many as comment! ThanksWrite a static method called "evaluate"...
In Java language Write a static method called "evaluate" that takes a string as a parameter. The string will contain a postfix expression, consisting only of integer operands and the arithmetic operators +, -, *, and / (representing addition, subtraction, multiplication, and division respectively). All operations should be performed as integer operations. You may assume that the input string contains a properly-formed postfix expression. The method should return the integer that the expression evaluates to. The method MUST use a stack...
Please use java language Thanks! Implement a recursive method called "pow" that takes 2 integers, x...
Please use java language Thanks! Implement a recursive method called "pow" that takes 2 integers, x and y, as parameters and returns the value xy (x raised to the power y). The exponent must be non-negative. If a negative argument is given for the exponent, then an exception should be thrown. Implement a recursive method called "fib" that takes a positive integer, n, as a parameter and returns the nth Fibonacci value. Assume that the first 2 values in the...
in Java language, in most simple algorithm Using a stack class, write a static method called...
in Java language, in most simple algorithm Using a stack class, write a static method called parse that parses a String for balanced parentheses. we seek only to determine that the symbol ‘{‘ is balanced with ‘}’. parse accepts a single String parameter and returns an int. If parse returns a minus 1, then there are no errors, otherwise, parse should return the position within the String where an error occurred. For example parse(“{3 + {4/2} }”)   would return -1...
Please use Java language! with as much as comment! thanks! Write a program that displays a...
Please use Java language! with as much as comment! thanks! Write a program that displays a frame with a three labels and three textfields. The labels should be "width:", "height:", and "title:" and should each be followed by one textfield. The texfields should be initialized with default values (Example 400, 600, default title), but should be edited by the user. There should be a button (label it whatever you want, I don't care). If you click the button, a new...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT