Answer to Question #307118 in Java | JSP | JSF for MP2

Question #307118

2. Write a program in Java to take the postfix form of a mathematical expression. Evaluate the postfix expression and print the result. The postfix expression will contain single-digit operands and ‘+’, ‘-‘, ‘*’, and ‘/’ operators. You can use relevant Java built-in classes in your code. The sample inputs/ outputs are given below: Sample inputs and outputs: (User’s inputs are shown in bold) The postfix expression: 543*+82/- The final result: 13


1
Expert's answer
2022-03-07T10:27:21-0500
import java.util.*;


public class Main {
  
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        
        int a = 0;
        int b = 0;
        
        int index = 0;
        int result = 0;
        
        while((index = input.indexOf('*')) >= 0){
          a = Character.getNumericValue(input.charAt(index - 2));
          b = Character.getNumericValue(input.charAt(index - 1));
          result = a * b;
          input = input.replaceFirst(String.format("[%d][%d][*]",a,b),String.format(";%d",result));
        }
        
         while((index = input.indexOf('/')) >= 0){
          a = Character.getNumericValue(input.charAt(index - 2));
          b = Character.getNumericValue(input.charAt(index - 1));
          result = a / b;
          input = input.replaceFirst(String.format("[%d][%d][/]",a,b),String.format(";%d",result));
        }
        
        String[] numbers = input.split("\\D");
        String[] operands = input.split("[\\;\\d]");
        int output = 0;
        
        for(int i = 0; i<numbers.length; i++){
          
          if(numbers[i].length() > 0){
            output = Integer.parseInt(numbers[i]);


              for(String operand: operands){
                if(operand.equals("+")){
                  for(int j = i+1; j<numbers.length; j++){ 
                    if(numbers[j].length() > 0){
                      output+=Integer.parseInt(numbers[j]);
                      i = j;
                      break;
                    }
                  }
                }else if(operand.equals("-")){
                  for(int j = i+1; j<numbers.length; j++){ 
                    if(numbers[j].length() > 0){
                      output-=Integer.parseInt(numbers[j]);
                      i = j;
                      break;
                    }
                  }
                }
              
              }
          }
          
          break;
        }
          System.out.println(output);
        }


    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS