Final touches - generalize Choose

Previous    Next    Home    Applet    Source    Package

Final cleanup - Generalize Choose to take a string of tokens as constructor argument. Every time through the loop of a Choose object the object's value changes to the next token in the argument string. After all tokens are used, an Up is thrown.

 
   import java.awt.*;
   import java.awt.event.*;
   import java.util.*;
   import javax.swing.*;
   import java.applet.*;
   
   interface Variable { void checkit() throws Up, Out;  String v();  }
   
   class Up extends Exception { }
   
   class Out extends Exception { }
   
   class Puzzle {
      public String v() { return ""; }
      public void assert_ (boolean e) throws Up { if (!e) throw new Up(); }
   }
   
   class Choose implements Variable {
      Variable next_for;
      String [] strs;
      String val;
      int n;
      
      public Choose(String s, Variable next_for) {  
         this.next_for = next_for;
         StringTokenizer t = new StringTokenizer(s," ");
         n = t.countTokens();
         strs = new String[n];
         for (int i=0 ; i < n ; i++) strs[i] = t.nextToken();
      }
   
      public String v() { return val; }
   
      public void checkit () throws Up, Out {
         for (int i=0 ; i < n ; i++)  {
            val = strs[i];
            try {  next_for.checkit();  } catch (Up up) { }
         }
         throw new Up();
      }
   }
   
   class Evaluate extends Puzzle implements Variable {
      Variable i,j,k;
      F problem;
   
      public Evaluate (F problem) {  
         this.problem = problem; 
         problem.out.append("\nSolve: ((1-i)*j + i*(1-k) + (1-j)*k)\n\n");
      }
      
      public void checkit() throws Up, Out {
         int iv = Integer.parseInt(i.v());
         int jv = Integer.parseInt(j.v());
         int kv = Integer.parseInt(k.v());
   
         assert_((((1-iv)*jv+iv*(1-kv)+(1-jv)*kv) % 2) == 1);
         problem.out.append("i="+iv+" j="+jv+" k="+kv+"\n");
         throw new Out();
      }
   
      public void solve () {
         try {
            k = new Choose("0 1", this);
            j = new Choose("0 1", k);
            i = new Choose("0 1", j);
            i.checkit();
         } catch (Up up) {
            problem.out.append("No solution\n");
         } catch (Out out) {  }
      }
   }
   
   public class F 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);
         eval.solve();
      }
   
      public void actionPerformed (ActionEvent evt) {  doit(); }
   }