20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions

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

       Previous     Next     Applet Source     All lectures

Exceptions for Escaping

Instructions: Write numbers, separated by blanks, into the left text box and hit return.
The left text box shows the product of the numbers and the right text box shows the
number of multiplications executed.

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

// Escape and do no multiplies if a number is 0
class MultiplyEscapeException extends Exception {

   MultiplyEscapeException () { }

   int escape () { return 0; }
}

class Multiply {
   String numbers;
   StringTokenizer t;
   int no_multiplied;  // Counts number of multiplies
   
   Multiply (String numbers) {
      no_multiplied = 0;
      this.numbers = numbers;
      t = new StringTokenizer(numbers, " ");
   }
   
   long multiply () throws MultiplyEscapeException { 
      try {
         long n = Integer.parseInt(t.nextToken());
         if (n == 0) throw new MultiplyEscapeException();
         long m = n * multiply();
         no_multiplied++;
         return m;
      }
      catch (NoSuchElementException e) {
         return 1;
      }
   }
}

class EscapeFrame extends JFrame implements ActionListener {
   JTextField out, nml;
   
   public EscapeFrame () {
      setLayout(new GridLayout(2,1));
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(new JLabel("Input: "));
      p.add(in = new JTextField(30));
      add(p);
      p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(new JLabel("  Output: "));
      p.add(out = new JTextField(5));
      p.add(new JLabel("  # multiplies: "));
      p.add(nml = new JTextField(5));
      add(p);
      out.setEditable(false);
      nml.setEditable(false);
      in.setBackground(Color.white);
      out.setBackground(Color.white);
      nml.setBackground(Color.white);
      in.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == in) {
         Multiply m = new Multiply(in.getText());
         try {
            out.setText(String.valueOf(m.multiply()));
         }
         catch (MultiplyEscapeException e) {
            out.setText("0");
         }
         nml.setText(String.valueOf(m.no_multiplied));
      }
   }
}

public class Escape extends Applet {
   public void init () {
      EscapeFrame ef = new EscapeFrame();
      ef.setSize(500,300);
      ef.setVisible(true);
   }
}