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
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);
}
}
Comments
Leave a comment