JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Write a program to find out delimiter matching using stack.


One of the common use of the stacks is to parse certain kinds of expressions or string text. Write a program that verifies the delimiters in a line of text or expression typed by the user. In this case we will take an arthimetic expression like a*(b+c)+[c/(a-b)]. We need to validate the expression such that the opening and closing brackets are proper or not.

a*(b+c) //This expression is right

b/[a*(b+c)] //This expression is right

{a*(b+c]} //This expression is wrong

package com.java2novice.ds.stack;

public class MyDelimiterMatching {

	public static void main(String a[]){
		MyDelimiterMatching mdm = new MyDelimiterMatching();
		String expression = "{(a+b)*(c+d)}";
		boolean result = mdm.isDelimiterMatching(expression);
		System.out.println(expression +" == "+result);
		
		expression = "{(a+b)+[x*(c+d)]}";
		result = mdm.isDelimiterMatching(expression);
		System.out.println(expression +" == "+result);
		
		expression = "{(a+b)+[x*(c+d)}}";
		result = mdm.isDelimiterMatching(expression);
		System.out.println(expression +" == "+result);
	}

	public boolean isDelimiterMatching(String inputExpr) {
		
		int stackSize = inputExpr.length();
		StackImpl theStack = new StackImpl(stackSize);
		for (int j = 0; j < inputExpr.length(); j++) {
			char ch = inputExpr.charAt(j);
			switch (ch) {
			case '{':
			case '[':
			case '(':
					theStack.push(ch);
					break;
			case '}':
			case ']':
			case ')':
					if (!theStack.isStackEmpty()) {
						char stackContent = theStack.pop();
						if ((ch == '}' && stackContent != '{') 
								|| (ch == ']' && stackContent != '[')
								|| (ch == ')' && stackContent != '(')){
							System.out.println("Mismatch found: " + ch + " at " + j);
							return false;
						}
					} else {
						System.out.println("Mismatch found: " + ch + " at " + j);
						return false;
					}
					break;
			default: break;
			}
		}
		if (!theStack.isStackEmpty()){
			System.out.println("Error: missing right delimiter");
			return false;
		}
		return true;
	}
}


class StackImpl {

	private int stackSize;
	private char[] stackArr;
	private int top;

	/**
	 * constructor to create stack with size
	 * @param size
	 */
	public StackImpl(int size) {
		this.stackSize = size;
		this.stackArr = new char[stackSize];
		this.top = -1;
	}

	/**
	 * This method adds new entry to the top 
	 * of the stack
	 * @param entry
	 * @throws Exception 
	 */
	public void push(char entry) {
		this.stackArr[++top] = entry;
	}

	/**
	 * This method removes an entry from the 
	 * top of the stack.
	 * @return
	 * @throws Exception 
	 */
	public char pop() {
		char entry = this.stackArr[top--];
		return entry;
	}
	
	/**
	 * This method returns top of the stack
	 * without removing it.
	 * @return
	 */
	public char peek() {
		return stackArr[top];
	}

	/**
	 * 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:
{(a+b)*(c+d)} == true
{(a+b)+[x*(c+d)]} == true
Mismatch found: } at 15
{(a+b)+[x*(c+d)}} == false
<< Previous Program | Next 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
Stream and types of Streams
A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are:

Byte Streams: Provide a convenient means for handling input and output of bytes. Byte Streams classes are defined by using two abstract classes, namely InputStream and OutputStream.

Character Streams: Provide a convenient means for handling input & output of characters. Character Streams classes are defined by using two abstract classes, namely Reader and Writer.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

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].

Most Visited Pages

Other Interesting Sites

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