King Fahd University of Petroleum and Minerals INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM ICS201, SECTIONS 52 Summer session 2001 (003 Semester) INTRODUCTION TO COMPUTER SCIENCE LAB #10 Stacks, Queues using arrays

Objectives:  To re-enforce our understanding of the different ADTs learnt in the lectures by viewing their respective demo applets  Lean how to improve the implementation of ADT’s using Java Exception Handling.  Learn how to use the ADT’s in other applications

1. Abstract Data Types Animation Applets. Click on each of the following links to visualize the various ADT’s in action:  Array Implementation of Stack  Array Implementation of Queue

2. Array Implementation of Stack ADT The implementation of Stack ADT using array of characters as discussed in the lectures can be found in the file, StackArray.java. This implementation uses StackOutOfBoundsException class defined in the file StackOutOfBoundsException.java. Open both these files and study them closely to understand them.

Example 1: The following example, StackArrayTest.java, makes use of the above class to implement a menu-driven program that allows the user to test the methods of the stack ADT. Open it, study it, compile and test-run it. import java.io.*; public class StackArrayTest { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); StackArray s = new StackArray(10); while (true) { System.out.println("\n1\tPush\n2\tPop\n3\tPeek\n4\tDisplay\n5\tQuit"); System.out.print("Enter your choice: "); char choice = stdin.readLine().charAt(0); try { switch (choice) { case '1': System.out.print("Enter Character Element: "); char ele = stdin.readLine().charAt(0); s.push(ele); break; case '2': System.out.println("popped: "+s.peek()); s.pop(); break; case '3': System.out.println("top element is: "+s.peek()); break; case '4': s.print(); System.out.println(); break; case '5': return; default: System.out.println("invalid command.."); } // end switch } //end try catch(StackOutOfBoundsException e) { System.out.println(e); } // end catach } } }

/** * @(#) StackArray.java * * Array implementation of a Stack ADT with exceptional handling * */ public class StackArray { private char[] items; private int maxSize; private int stackTop;

/** * Constructor to Create new instance of a Stack * of specified size * * @param size of new stack */ public StackArray(int size) { maxSize = size; items = new char[maxSize]; stackTop = -1; } /** * Test if stack is empty * * @return true if the stack is empty, false otherwise */ public boolean isEmpty() { return stackTop == -1; }

/** * Test if stack is full. This method is only required in * this implementation as the array implementation imposes * an upper stack size. * * @return true if the stack is full, false otherwise */ public boolean isFull() { return stackTop == maxSize-1; }

/** * push an element onto top of the stack * * @param element to push onto stack */ public void push(char c) throws StackOutOfBoundsException { if (isFull()) throw new StackOutOfBoundsException("Opps! Stack is Full"); else items[++stackTop] = c; }

/** * Obtain copy of top element on stack * * @return top element */ public char peek(){ if (isEmpty()) throw new StackOutOfBoundsException("Sorry! Stack is Empty"); else return items[stackTop]; } /** * * remove top element on stack */ public void pop() { if (isEmpty()) throw new StackOutOfBoundsException("Afwan! Stack is Empty"); else stackTop--; } public String toString() { StringBuffer buffer = new StringBuffer();

buffer.append("Stack( "); for(int i=stackTop; i>=0; i--) { buffer.append(items[i]+" "); } buffer.append(")"); return buffer.toString(); } /** * Print Elements in Stack on Standard Output * */ public void print() { System.out.println(this); } } class StackOutOfBoundsException extends IndexOutOfBoundsException { public StackOutOfBoundsException() {} // default constructor

public StackOutOfBoundsException(String problem) { super(problem); // let superclass constructor handle the argument } }

3. Array Implementation of Queue ADT The implementation of Queue ADT using array of characters as discussed in the lectures can be found in the file, QueueArray.java. This Example 2: The following example, QueueArrayTest.java, makes use of the above class to implement a menu-driven program that allows the user to test the methods of the Queue ADT. Open it, study it, compile and test-run it. import java.io.*; public class QueueArrayTest {

public static void main(String[] arg) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); QueueArray q = new QueueArray(10);

while (true) { System.out.println("1\tEnqueue\n2\tDequeue\n3\tFront\n4\tDisplay\n5\tSize\n6\tQuit"); System.out.print("Enter your choice: "); char choice = stdin.readLine().charAt(0); switch (choice) { case '1': System.out.print("Enter Character Element: "); char ele = stdin.readLine().charAt(0); if (!q.isFull()) q.enqueue(ele); else System.out.println("Sorry, Queue is Full"); break; case '2': if (!q.isEmpty()) { System.out.println("Dequed: "+q.front()); q.dequeue(); } else System.out.println("Sorry, Queue is Empty"); break; case '3': if (!q.isEmpty()) System.out.println("front element is: "+q.front()); else System.out.println("Sorry, Queue is Empty"); break; case '4': q.print(); break; case '5': System.out.println("Queue size="+q.size()); break; case '6': return; default: System.out.println("invalid command.."); } } }

}

Notes: Comparing Example 1 and Example 2 we can observe two major advantages of using Exception handling provided by Java. 1. 1. Security: Because StackOutOfBoundsException is derived from Exception which is a checked exception, the compiler will not allow any applications that makes use of any of the methods push(), pop() and peek() to compile unless there is some specification on what to do if StackOutOfBoundsException occurs. Thus, using exceptions as in Example 1 forces the programmer to write a more secure programs.

2. 2. Shorter Code: Using exception handling, we can use one try-catch statement to handle multiple calls of the methods that throw exceptions as seen in Example 1: In example 2 we had to use an if statement for each call to any of the methods that throw exceptions. implementation does not handle exceptions. Thus, the user must check for possible errors when using this class.

, QueueArray.java /** /** * @(#) QueueArray.java * Test if queue is empty */ * /** * @return true if queue is empty, false otherwise * Implements a Queue ADT Using a Circular Array Implementation. */ * This simple implementation is limited to storing 'char' types. public boolean isEmpty() { */ return (nItems==0); public class QueueArray { } private int maxSize; private char[] queArray; /** private int front; * Test if queue is full private int rear; * private int nItems; * @return true if queue is full, false otherwise /** */ * Constructor to create a queue of specified size public boolean isFull() { * return (nItems==maxSize); * @param s size of queue } */ public QueueArray(int s) { /** maxSize = s; * Return size of queue queArray = new char[maxSize]; * front = 0; * @return queue size rear = -1; */ nItems = 0; public int size() { } return nItems; } /** * Add item to rear of queue * /** * @param j item to add to queue * Convert Queue into a String representation. */ * public void enqueue(char c) { * @return new String object representation of Queue rear = (rear+1) % maxSize; */ queArray[rear] = c; public String toString() { nItems++; StringBuffer buffer = new StringBuffer(); } buffer.append("Queue( "); /** for(int i=front,n=0; n

Assignment: 1. 1. (a) Write a class, QueueOutOfBoundsException, similar to StackOutOfBoundsException and use it to modify the Array implementation of Queue ADT so that the methods, enqueue(), dequeue() and front() thow this exception. (b) (b) Modify Example 2, QueueArrayTest.java, so that it handle QueueOutOfBoundsException instead of using if statements.

2. 2. Complete the Program in the File, StackBracketTest.java, so that is checks whether the brackets, {}, [], and (), in a given string match or not. Hint: Use stack to check whether such algebraic expressions have properly balanced parentheses or not. To do this, we start

with an empty stack and scan a string representing the algebraic expression from left to right. Whenever we encounter a left parenthesis(, a left bracket [, or a left brace {, we push it onto the stack. Whenever we encounter a right parenthesis ), a right bracket ], or a right braced }, we pop the top item off the stack and check to see that its type matches the type of right parenthesis bracket, or brace encountered. If the stack is empty by the time we get to the end of the expression string and if all pairs of matched parentheses were of the same type, the expression has properly balanced parentheses. Otherwise, the parentheses are not