20-CS-694 Advanced Programming Techniques Spring 2012

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

    Previous     Next     All lectures        Code     Exception Hierarchy    

Add Out Exception Class for Control

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

interface Variable { 
   void checkit() throws Up, Out;  int v();  

class Up extends Exception { }

class Out extends Exception { }

class Puzzle {
   public int v() { return 0; }
   public void assert_ (boolean e) throws Up { 
      if (!e) throw new Up(); 

class Choose implements Variable {
   Variable next_for;
   int val = 0;
   Choose (Variable next_for) { 
      this.next_for = next_for; 

   public void checkit () throws Up, Out {
      for ( ; val < 2 ; val++) 
         try { next_for.checkit(); } catch (Up up) { } 
      val = 0;
      throw new Up();

   public int v() { return val; }

class Evaluate 
   extends Puzzle implements Variable {
   Variable i,j,k;
   PuzzleFrame f;

   public Evaluate (PuzzleFrame f) {  
      this.f = f; 
      f.out.append("\nSolve: ((1-i)*j + i*(1-k) + (1-j)*k)");
   public void checkit() throws Up, Out {
                (1-j.v())*k.v()) % 2) == 1);
      f.out.append("i="+i.v()+" j="+j.v());
		f.out.append(" k="+k.v()+"\n");
      throw new Out();

   public void solve () {
      try {
         k = new Choose(this);
         j = new Choose(k);
         i = new Choose(j);
      } catch (Up up) {
         f.out.append("No solution\n");
      } catch (Out out) {  }

class PuzzleFrame 
   extends JFrame implements ActionListener {
   JTextArea out;
   JButton button;

   public PuzzleFrame () {
      setLayout(new FlowLayout());
      add(new JScrollPane(out = new JTextArea(16,30)));
      add(button = new JButton("Press Me"));
      out.setFont(new Font("TimesRoman", Font.PLAIN, 18));

   public void doit() {
      Evaluate eval = new Evaluate(this);

   public void actionPerformed (ActionEvent evt) {  

public class puzzle 
   extends Applet implements ActionListener {
   JButton go;

   public void init () {
      setLayout(new BorderLayout());
      setBackground(new Color(255,255,223));
      add("Center", go = new JButton("Applet"));

   public void actionPerformed (ActionEvent evt) {
      PuzzleFrame hf = new PuzzleFrame();
 -  In order to stop at the first solution we define an Out exception to be used in checkit() of Evaluate in case assert_() succeeds. An Out exception is only caught at the top level in solve of Evaluate. Therefore, throwing an Out terminates computation (after a solution is printed before throwing it). If the top level is reached via a thrown Up, there is no solution and a message is printed.

To streamline the coding process for future users the Puzzle class is created to hold v(), which is required by the Variable interface, and assert_(), which should never change from use to use.