Java Code

profileWernerrab
SP2020_InfixedExpressionEvaluation_Acharya.java

package Pack; import java.util.*; import java.io.*; public class SP2020_InfixedExpressionEvaluation_Acharya { public int evaluate(String expression){ //Stack for Numbers Stack<Integer> numbers = new Stack<>(); //Stack for operators Stack<Character> operations = new Stack<>(); StringTokenizer tokens = new StringTokenizer(expression, "+-*/()", true); while(tokens.hasMoreTokens()){ String tkn = tokens.nextToken(); if(tkn.matches("[0-9]+")){ numbers.push(Integer.parseInt(tkn)); }else if(tkn.charAt(0)=='(' ) { operations.push(tkn.charAt(0)); }else if(tkn.charAt(0)==')'){ while(operations.peek()!='('){ int output = performOperation(numbers, operations); numbers.push(output); } operations.pop(); }else if(isOperator(tkn.charAt(0))){ while(!operations.isEmpty() && precedence(tkn.charAt(0))<=precedence(operations.peek())){ int output = performOperation(numbers, operations); numbers.push(output); } operations.push(tkn.charAt(0)); } } while(!operations.isEmpty()){ int output = performOperation(numbers, operations); //push it back to stack numbers.push(output); } return numbers.pop(); } static int precedence(char c){ switch (c){ case '+': case '-': return 1; case '*': case '/': return 2; } return -1; } public int performOperation(Stack<Integer> numbers, Stack<Character> operations) { int a = numbers.pop(); int b = numbers.pop(); char operation = operations.pop(); switch (operation) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': if (a == 0) throw new UnsupportedOperationException("Cannot divide by zero"); return b / a; } return 0; } public boolean isOperator(char c){ return (c=='+'||c=='-'||c=='/'||c=='*'); } public static void main(String[] args) throws Exception { String infixExpression; Scanner s=new Scanner(System.in); System.out.println("Choose type \n1.EXPRESSION FROM THE KEYBOARD\n2.EXPRESSION FROM THE INPUT FILE\n"); int type=s.nextInt(); SP2020_InfixedExpressionEvaluation_Acharya i = new SP2020_InfixedExpressionEvaluation_Acharya(); if(type==1){ String emp=s.nextLine(); infixExpression=s.nextLine(); System.out.println("SP2020_InfixedExpressionEvaluation_Acharya.java"); System.out.println("EXPRESSION FROM THE KEYBOARD"); System.out.println(infixExpression+"="+i.evaluate(infixExpression)); }else if(type==2){ System.out.println("SP2020_InfixedExpressionEvaluation_Acharya.java"); System.out.println("EXPRESSION FROM THE FILE expression.txt"); File file = new File("expression.txt"); Scanner sc = new Scanner(file); while (sc.hasNextLine()){ String exp=sc.nextLine(); System.out.println(exp+"="+i.evaluate(exp)); } } } }