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

A nested for loop

 Given three variables, i,j,k which take value 0 or 1, we want to find values for these values that cause a logical expression such as     ¬i ∧ j ⊕ i ∧ ¬k ⊕ ¬j ∧ k to evaluate to 1, where ∧ means logical 'and', ¬ means 'not' and ⊕ means 'exclusive-or'. This can be solved using three nested for loops as shown in this slide. Variables are declares as integers but are assigned values only from the set {0,1}. Then the multiplication x*y corresponds to x ∧ y, (1-x) corresponds to ¬x, and (x+y)%2 corresponds to x ⊕ y. ``` import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.*; public class A 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() { // Variables i,j,k will take value 0,1 only (Boolean) // ((1-i)*j + i*(1-k) + (1-j)*k) is then a logic expression // where '*' is 'and', '1-' is 'not' and '+' is 'exclusive-or' // What values of i,j,k make true (that is, give it value 1)? boolean done = false; for (int i=0 ; i < 2 && !done ; i++) { for (int j=0 ; j < 2 && !done ; j++) { for (int k=0 ; k < 2 && !done ; k++) { if ( (((1-i)*j + i*(1-k) + (1-j)*k) % 2) == 1 ) { out.append("i="+i+" j="+j+" k="+k+"\n"); done = true; } } } } if (!done) out.append("There is no solution!\n"); } public void actionPerformed (ActionEvent evt) { doit(); } } ```