Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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.
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) { Stackstack = 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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started