20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions

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

    Previous     Next     All lectures        Code     Exception Hierarchy    

Exceptions for Program Control

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

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"));
      button.addActionListener(this);
      out.setFont(new Font("TimesRoman", Font.PLAIN, 18));
   }

   public void doit() {
      // Variables i,j,k will take value 0,1 only
      // (Boolean) ((1-i)*j + i*(1-k) + (1-j)*k) is then a
      // logic expression where '*' is 'and', '1-' is 'not'
      // and '+' is 'exclusive-or' What values of i,j,k
      // make true (that is, give it value 1)?
      out.append("\nSolve: ((1-i)*j + i*(1-k) + (1-j)*k)");
      out.append("\n\n");
      boolean done = false;
      for (int i=0 ; i < 2 && !done ; i++) {
         for (int j=0 ; j < 2 && !done ; j++) {
            for (int k=0 ; k < 2 && !done ; k++) {
               if ((((1-i)*j+i*(1-k)+(1-j)*k)%2) == 1) {
                  out.append(" i="+i+" j="+j+" k="+k+"\n");
                  done = true;
               }
            }
         }
      }
      if (!done) out.append("There is no solution!\n");
   }

   public void actionPerformed (ActionEvent evt) {  
      doit(); 
   }
}

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"));
      go.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      PuzzleFrame hf = new PuzzleFrame();
      hf.setSize(550,450);
      hf.setVisible(true);
   }
}
 -  Given three variables, i,j,k which take value 0 or 1, we want to find values for these values that cause a logical expression such as

    ¬i j i ∧ ¬k ⊕ ¬j k

to evaluate to 1, where ∧ means logical 'and', ¬ means 'not' and ⊕ means 'exclusive-or'. This can be solved using three nested for loops as shown in this slide. Variables are declares as integers but are assigned values only from the set {0,1}. Then the multiplication x*y corresponds to x y, (1-x) corresponds to ¬x, and (x+y)%2 corresponds to x y.

A simple solution is to implement nested for loops, one for each variable, to set values. A potential problem is that nesting can be deep and awkward. This sequence of slides flattens this out with exceptions.