Question: My program takes an infix expression from the user and converts it to postfix. However also need my program to be able to take the

My program takes an infix expression from the user and converts it to postfix.

However also need my program to be able to take the postfix expression it has made and evaluate it as a double and print the answer.

**I need my code to be edited and not a whole new program

Here is my code

import java.util.Stack; import java.util.Scanner; public abstract class infixToPostfix { 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); 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!