Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package Question2;
- import Question1.MyStack;
- import java.util.Scanner;
- /**
- *
- * @author CSC2017
- */
- public class EvalExpression {
- private static MyStack<Integer> numStack = new MyStack<>();
- private static MyStack<Character> opStack = new MyStack<>();
- public static void main(String[] args) {
- Scanner s = new Scanner(System.in);
- System.out.println("Enter Expression: ");
- String exprsion = s.nextLine();
- int value = eval(exprsion);
- System.out.println(exprsion+" = "+value);
- }
- public static int eval(String exprsion){
- int result = 0;
- for(char c:exprsion.toCharArray()){
- if((int)c <= 57 && (int)c >=48){
- //char c is a number
- numStack.push((int)c - 48);
- }else{
- //if not a number then an operator
- if(opStack.empty()){
- //no operands pushed yet
- opStack.push(c);
- }else{
- //operands inside
- char topOp = opStack.peek();
- if(isHigherOperand(topOp,c)){
- do{
- topOp = opStack.pop();
- int num1 = numStack.pop();
- int num2 = numStack.pop();
- int value = evalOperation(num2,topOp,num1);
- numStack.push(value);
- topOp = opStack.peek();
- }while(isHigherOperand(topOp,c));
- opStack.push(c);
- }else{
- opStack.push(c); }
- }
- }
- }
- if(!opStack.empty()){
- while(!opStack.empty()){
- char topOp = opStack.pop();
- int num1 = numStack.pop();
- int num2 = numStack.pop();
- int value = evalOperation(num2,topOp,num1);
- numStack.push(value);
- }
- }
- result = numStack.pop();
- return result;
- }
- public static boolean isHigherOperand(char firstOp,char secOp){
- //returns true if first operand greater than second
- if(firstOp == '*' || firstOp == '/') return true; //assuming the operaots are + - * /
- else return false;
- }
- public static int evalOperation(int num1,char topOp,int num2){
- int value = 0;
- switch(topOp){
- case '+':
- value = num1+num2;
- break;
- case '-':
- value = num1-num2;
- break;
- case '*':
- value = num1*num2;
- break;
- case '/':
- value = num1/num2;
- break;
- default:
- value = 0;
- break;
- }
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement