CS7 Notes from Feb. 2, 2004 So Far Our programs have been sequential only - Limiting and not interesting - We want our programs to make decisions - concept is based on Booleans (true, false) e.g. IQ System.out.print(“Enter for your IQ:”); IQ = Console.in.readInt(); If ( IQ >= 140) System.out.println(“You are smart!”); System.out.println(“Thanks for playing!”); - Without braces, the if statement will include only one line of code (the "smart" line). - Thus, the second println statement ("Thanks..") will always execute, no matter what (it comes after the if). - If you add braces, you can have any number of lines in the body of the if: If ( IQ >= 140) { System.out.println("You are smart!"); System.out.println("and sexy."); } System.out.println("Thanks for playing!"); Building boolean expressions: - Relational Operators: <, >, = =, != - Logical Operators: &&(and), || (or), !(Not) To get a true result: - and (&&), both parts must be true - or (||), either part must be true - not (!), expression must be false - Anything else, you get false as the result. e.g. Is the age between 18 and 25 inclusive? if ((age > = 18) && (age < = 25)) System.out.println(“You pay higher insurance”); e.g. Are you an even numbered age? if (age % 2 == 0) System.out.println("an even age!"); Variatons on condition: !(age % 2 == 0) ==> checks for oddness (negation of even) (age % 2 == 1) ==> checks for oddness (looks for a 1 remainder) (age % 2 != 0) ==> again checks for oddness (looks for nonzero rem.) Note: - In general, to check divisibility by n, just % by n and look for a zero remainder. if (a % n == 0) System.out.println(a + " is evenly divisible by " + n); e.g. Is your age less than 6 or greater than 60? If ( age < = 6 || age >= 60) System.out.println("Passenger needs assistance.");