/************************ * Examples of booleans, the "if" conditional, and the "while" loop. * This material is chapter 4 in our text. * * These new constructs give us *lots* more power; * please look carefully at the code. * * Things to discuss: * - "static" methods, and what it means to say that * - "public" vs "private" methods * - method definitions, calling the method, and their * inputs (i.e. variables passed in) and output (i.e. return value) * * * @author Jim mahoney * @version Oct 8 ************************/ class BooleanExamples { public static void main(String[] args){ testDeMorgan(); } // Loop through all four true/false combinations of two // boolean variables, and use each to try de Morgan's Laws. public static void testDeMorgan(){ final int numberOfCases=4; line(); print("Testing de Morgan's Laws."); line(); boolean a=true; boolean b=true; int howManyTrue = 0; int whichCase=1; while (whichCase <= numberOfCases){ if (1==whichCase){ a=true; b=true; } else if (2==whichCase){ a=true; b=false; } else if (3==whichCase){ a=false; b=true; } else if (4==whichCase){ a=false; b=false; } else { print(" OOPS - illegal whichCase"); System.exit(1); // exit the program with an error status. } boolean answer = tryOneDeMorganPair(a,b); if (answer) { howManyTrue++; } whichCase++; } print(" Summary: de Morgan is true " + howManyTrue + " times out of " + numberOfCases + "."); } // Print out an analysis of a specific true/false combination // in the symbolic logic truism called "de Morgan's Law". (See pg 135.) public static boolean tryOneDeMorganPair(boolean x, boolean y){ print(" Trying x='" + x + "', y='" + y + "' on deMorgan."); boolean leftSide = !(x && y); boolean rightSide = !x || !y; boolean wholeThing = (leftSide == rightSide); print(" Left side : !(x && y) = " + leftSide + "."); print(" Right side : !x || !y = " + rightSide + "."); print(" (Left == Right) is " + wholeThing + "."); line(); return wholeThing; } // Print a line of dashes, i.e. " - - - - - - - - - " public static void line(){ int iDashCount=20; System.out.print(">"); while (iDashCount>0){ System.out.print(" -"); iDashCount--; } System.out.println(" "); } // I get tired of typing "System.out.println". // So this lets me just type "print". public static void print(String s){ System.out.println("> "+s); } }