20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions for control

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

       Previous     Next     Applet Source     All lectures

Evaluate begins to look good

Things are looking better because the Choose instantiations have been moved to Evaluate. Now we can try to generalize this so the control structure can be reused for a variety of problems.

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

   interface Variable { boolean checkit();  int v();  }
   
   class Choose implements Variable {
      Variable next_for;
      int val = 0;
      
      Choose (Variable next_for) { this.next_for = next_for; }
   
      public boolean checkit () {
         for ( ; val < 2 ; val++) if (next_for.checkit()) return true;
         val = 0;
         return false;
      }
   
      public int v() { return val; }
   }
   
   class Evaluate implements Variable {
      Variable i,j,k;
      C problem;
   
      public Evaluate (C problem) {  
         this.problem = problem; 
         problem.out.append("\nSolve: ((1-i)*j + i*(1-k) + (1-j)*k)\n\n");
      }
      
      public boolean checkit () {
         if ( (((1-i.v())*j.v() + i.v()*(1-k.v()) + (1-j.v())*k.v()) % 2) == 1 ) {
            problem.out.append("i="+i.v()+" j="+j.v()+" k="+k.v()+"\n");
            return true;
         }
         return false;
      }
   
      public boolean solve () {
         k = new Choose(this);
         j = new Choose(k);
         i = new Choose(j);
         return i.checkit();
      }
   
      public int v() { return 0; }
   }
   
   public class C extends Applet implements ActionListener {
      JTextArea out;
      JButton button;
   
      public void init () {
         setLayout(new FlowLayout());
         add(new JScrollPane(out = new JTextArea(16,30)));
         add(button = new JButton("Press Me"));
         button.addActionListener(this);
      }
   
      public void doit() {
         Evaluate eval = new Evaluate(this);
         if (!eval.solve()) out.append("There is no solution!\n");
      }
   
      public void actionPerformed (ActionEvent evt) {  doit(); }
   }