JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Evaluation of an infix expression that is fully parenthesized using stack in java.


Infix notation is the common arithmetic and logical formula notation, in which operators are written infix-style between the operands they act on (e.g. 2 + 2). It is not as simple to parse by computers as prefix notation ( e.g. + 2 2 ) or postfix notation ( e.g. 2 2 + ), but many programming languages use it due to its familiarity.

Here are the steps to evaluate infix expression which is fully parenthesized using stack.

	1. Read one input character
  	2. Actions at end of each input
     	   Opening brackets         (2.1)  Push into stack and then Go to step (1)
     	   Number                        (2.2)  Push into stack and then Go to step (1)
     	   Operator                      (2.3)  Push into stack and then Go to step (1)
     	   
     	   Closing brackets            (2.4)  Pop from character stack
                                   		 (2.4.1) Pop is used four times
                                           		The first popped element is assigned to op2
                                           		The second popped element is assigned to op
                                           		The third popped element is assigned to op1
                                           		The fourth popped element is the remaining opening bracket, 
                                           		which can be discarded.
                                           		Evaluate op1 op op2
                                           		Convert the result into character and 
                                           		push into the stack
                                           		
    		New line character           (2.5)  Pop from stack and print the answer
                                         		STOP


package com.java2novice.ds.stack;

import java.util.StringTokenizer;

public class InfixFullParantEx {

	public static String evaluateInfix(String exps){
		
		/**remove if any spaces from the expression**/
		exps = exps.replaceAll("\\s+", "");
		/**we assume that the expression is in valid format**/
		MyGenericsStack<String> stack = new MyGenericsStack<String>(exps.length());
		/**break the expression into tokens**/
		StringTokenizer tokens = new StringTokenizer(exps, "{}()*/+-", true);
		while(tokens.hasMoreTokens()){
			String tkn = tokens.nextToken();
			/**read each token and take action**/
			if(tkn.equals("(") 
					|| tkn.equals("{")
					|| tkn.matches("[0-9]+") 
					|| tkn.equals("*")
					|| tkn.equals("/")
					|| tkn.equals("+")
					|| tkn.equals("-")){
				/**push token to the stack**/
				stack.push(tkn);
			} else if(tkn.equals("}") || tkn.equals(")")){
				try {
					int op2 = Integer.parseInt(stack.pop()); 
					String oprnd = stack.pop();
					int op1 = Integer.parseInt(stack.pop());
					/**Below pop removes either } or ) from stack**/
					if(!stack.isStackEmpty()){
						stack.pop();
					}
					int result = 0;
					if(oprnd.equals("*")){
						result = op1*op2;
					} else if(oprnd.equals("/")){
						result = op1/op2;
					} else if(oprnd.equals("+")){
						result = op1+op2;
					} else if(oprnd.equals("-")){
						result = op1-op2;
					}
					/**push the result to the stack**/
					stack.push(result+"");
				} catch (Exception e) {
					e.printStackTrace();
					break;
				}
			}
		}
		String finalResult = "";
		try {
			finalResult = stack.pop();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return finalResult;
	}
	
	public static void main(String a[]){
		String expr = "((2*5)+(6/2))";
		System.out.println("Expression: "+expr);
		System.out.println("Final Result: "+evaluateInfix(expr));
		expr = "(((2 * 5) - (1 * 2)) / (11 - 9))";
		System.out.println("Expression: "+expr);
		System.out.println("Final Result: "+evaluateInfix(expr));
		
	}
}

/**
 * Stack implementation
 */
public class MyGenericsStack<T extends Object> {

	private int stackSize;
	private T[] stackArr;
	private int top;
	
	/**
	 * constructor to create stack with size
	 * @param size
	 */
	@SuppressWarnings("unchecked")
	public MyGenericsStack(int size) {
		this.stackSize = size;
		this.stackArr = (T[]) new Object[stackSize];
		this.top = -1;
	}

	/**
	 * This method adds new entry to the top 
	 * of the stack
	 * @param entry
	 * @throws Exception 
	 */
	public void push(T entry){
		if(this.isStackFull()){
			System.out.println(("Stack is full. Increasing the capacity."));
			this.increaseStackCapacity();
		}
		System.out.println("Adding: "+entry);
		this.stackArr[++top] = entry;
	}

	/**
	 * This method removes an entry from the 
	 * top of the stack.
	 * @return
	 * @throws Exception 
	 */
	public T pop() throws Exception {
		if(this.isStackEmpty()){
			throw new Exception("Stack is empty. Can not remove element.");
		}
		T entry = this.stackArr[top--];
		System.out.println("Removed entry: "+entry);
		return entry;
	}
	
	/**
	 * This method returns top of the stack
	 * without removing it.
	 * @return
	 */
	public T peek() {
		return stackArr[top];
	}

	private void increaseStackCapacity(){
		
		@SuppressWarnings("unchecked")
		T[] newStack = (T[]) new Object[this.stackSize*2];
		for(int i=0;i<stackSize;i++){
			newStack[i] = this.stackArr[i];
		}
		this.stackArr = newStack;
		this.stackSize = this.stackSize*2;
	}
	
	/**
	 * This method returns true if the stack is 
	 * empty
	 * @return
	 */
	public boolean isStackEmpty() {
		return (top == -1);
	}

	/**
	 * This method returns true if the stack is full
	 * @return
	 */
	public boolean isStackFull() {
		return (top == stackSize - 1);
	}
}


Output:
Expression: ((2*5)+(6/2))
Adding: (
Adding: (
Adding: 2
Adding: *
Adding: 5
Removed entry: 5
Removed entry: *
Removed entry: 2
Removed entry: (
Adding: 10
Adding: +
Adding: (
Adding: 6
Adding: /
Adding: 2
Removed entry: 2
Removed entry: /
Removed entry: 6
Removed entry: (
Adding: 3
Removed entry: 3
Removed entry: +
Removed entry: 10
Removed entry: (
Adding: 13
Removed entry: 13
Final Result: 13
Expression: (((2 * 5) - (1 * 2)) / (11 - 9))
Adding: (
Adding: (
Adding: (
Adding: 2
Adding: *
Adding: 5
Removed entry: 5
Removed entry: *
Removed entry: 2
Removed entry: (
Adding: 10
Adding: -
Adding: (
Adding: 1
Adding: *
Adding: 2
Removed entry: 2
Removed entry: *
Removed entry: 1
Removed entry: (
Adding: 2
Removed entry: 2
Removed entry: -
Removed entry: 10
Removed entry: (
Adding: 8
Adding: /
Adding: (
Adding: 11
Adding: -
Adding: 9
Removed entry: 9
Removed entry: -
Removed entry: 11
Removed entry: (
Adding: 2
Removed entry: 2
Removed entry: /
Removed entry: 8
Removed entry: (
Adding: 4
Removed entry: 4
Final Result: 4
<< Previous Program 

List of Stack Data Structure Examples

  1. Stack introduction & implementation
  2. Java Dynamic Stack Implementation
  3. Stack implementation using generics bounded type.
  4. Reverse a word or string using Stack data structure.
  5. Write a program to find out delimiter matching using stack.
  6. Convert a decimal into a binary number using stack.
  7. Towers of Hanoi implementation using stack.
  8. Evaluation of an infix expression that is fully parenthesized using stack in java.
Knowledge Centre
Purpose of garbage collection
The garbage collection process is to identify the objects which are no longer referenced or needed by a program so that their resources can be reclaimed and reused. These identified objects will be discarded.
Famous Quotations
You can never get enough of what you don’t really need.
-- Eric Hoffer

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected] or you can comment on the page.

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2017 by Nataraja Gootooru. All Rights Reserved.