20-CS-4003-001 Organization of Programming Languages Fall 2017
Exceptions

Lambda calculus, Type theory, Formal semantics, Program analysis

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

   public Evaluate (Exception_6Frame f) {  
      this.f = f; 
      f.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 ) {
         f.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; }
}

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

   public Exception_6Frame () {
      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 exception_6 
   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) {
      Exception_6Frame hf = new Exception_6Frame();
      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.