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    

Evaluate Begins to Look Good

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;
   PuzzleFrame f;

   public Evaluate (PuzzleFrame f) {  
      this.f = f; 
      f.out.append("\nSolve: ((1-i)*j+i*(1-k)+(1-j)*k)");
      f.out.append("\n\n");
   }
   
   public boolean checkit () {
      if ( (((1-i.v())*j.v() + i.v()*(1-k.v()) +
	     (1-j.v())*k.v()) % 2) == 1 ) {
         f.out.append("i="+i.v()+" j="+j.v());
         f.out.append(" 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; }
}

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() {
      Evaluate eval = new Evaluate(this);
      if (!eval.solve()) out.append("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);
   }
}
 -  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.