On page 122 there is a Stack class and a test program for that class. This assignment will be to improve this program. One problem that we will correct is that the data that is returned from the pop method can be valid data or indicate an error. The errors are indicated by returning -1, but that can be a valid integer value. By using exceptions we can indicate errors by having the push and pop methods throw an exception. Then the errors will be separated from the data. Assignment:
The assignment is to rewrite the Stack class example program from page 126 in the following ways:
package stack; /** * @author bford */ public class Stack implements StackIntf { int[] array = new int[10]; int tos; Stack() { tos = -1; } public void push(int val) { if (tos == 9) { System.out.println("Stack Full"); } else { array[++tos] = val; } } public int pop() { if (tos < 0) { System.out.println("Stack Empty"); return -1; } else { return array[tos--]; } } public boolean full() { return tos == 9; } public boolean empty() { return tos < 0; } public static void main(String[] args) { Stack s = new Stack(); for (int i = 0; i < 13; i++) { if (s.full()) { System.out.println("Stack Already full, can't put: " + i); } else { s.push(i); } } while (s.empty() == false) { System.out.println("popped: " + s.pop()); } } }
package stack; /** * @author bford */ public interface StackIntf { // puts a value on the Stack void push(int value); // retrieves a value from the Stack int pop(); // returns true if a value cannot be pushed onto the Stack boolean full(); // returns true if a value cannot be retrieved from the Stack boolean empty(); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package exceptionexample; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author bford */ public class ExceptionExample { static void method1() throws BPFException { try { // start of try block. NOTE: block ( { } ) required int a = 0; int b = 5; int c = b / a; // divide by zero exception is generated here // due to previous exception, next line is not executed System.out.println("c = " + c); } // end of try block catch (ArithmeticException e) { // start catch block System.out.println("Exception Caught: " + e); e.printStackTrace(); throw new BPFException(e); } // end catch block finally { System.out.println("Finally clause: This is always executed"); } } public static void main(String[] args) { try { method1(); } catch (BPFException ex) { Logger.getLogger(ExceptionExample.class.getName()).log(Level.SEVERE, null, ex); } } }
package exceptionexample; /** * * @author bford */ public class BPFException extends Exception { BPFException(Exception e) { super(e); } public String toString() { return "BPFException toString() method: " + super.toString(); } }