Question: My program takes an infix expression from the user and converts it to postfix. However I need for my program to also calculate the postfix
My program takes an infix expression from the user and converts it to postfix. However I need for my program to also calculate the postfix expression as a double.
Here is my code
import java.util.Stack; import java.util.Scanner; public abstract class MyClass { static int getPrecedence(char checkChar) { if (checkChar == '+' || checkChar == '-') return 1; if (checkChar == '*' || checkChar == '/') return 2; if (checkChar == '(' || checkChar == ')') return 0; return -1; } // function which returns true if expression is valid static boolean valid(String expr) { // String containing valid characters only String characters = "0123456789+-*/^()"; // Now checking for validation if (expr.length() >= 3 && expr.length() <= 20) { for (int i = 0; i < expr.length(); i++) { if (!characters.contains("" + expr.charAt(i))) return false; } return true; } else { return false; } } public static void main(String[] args) { Stack stack = new Stack(); Scanner scanner = new Scanner(System.in); String result = ""; String inputStr; // using while loop to take input expression until input is invalid while (true) { System.out.print("Enter expression: "); inputStr = scanner.nextLine(); // passing input expression to valid function() if (valid(inputStr)) break; else { // printing invalid expression message and asking again to input System.out.println("Invalid Expression! Your expression must be 3-20 characters long and can only use single digits 0-9 and +, -, *, /, ^, (, )"); } } char[] inputCharArray = inputStr.toCharArray(); for (int i = 0; i < inputCharArray.length; i++) { char checkChar = inputCharArray[i]; if (checkChar != '+' && checkChar != '-' && checkChar != '/' && checkChar != '*' && checkChar != '(' && checkChar != ')') { result = result + checkChar; } else { if (checkChar != '(' && checkChar != ')') { if (stack.isEmpty()) { stack.push(checkChar); } else { while (getPrecedence(stack.peek()) >= getPrecedence(checkChar)) { result = result + stack.pop(); if (stack.isEmpty()) break; } stack.push(checkChar); } } else { if (checkChar == '(') stack.push(checkChar); else { while (stack.peek() != '(') { result = result + stack.pop(); } stack.pop(); } } } } while (!stack.isEmpty()) result = result + stack.pop(); System.out.println(result); } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
