Lab 8: IF statement. Conditionals and Loops
The if condition Statement A conditional statement lets us choose which statement will be executed next if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.
Logic of an if statement condition evaluated true statement false Can use if to code things like: if total > 100 print $ + total / 100
The if-else Statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both
Logic of an if-else statement Can use if to code things like: if total > 100 print $ + total / 100 else print total + cents condition evaluated true statement1 false statement2
Logic of an if-else statement Boolean expression Can use if to code things like: if total > 100 print $ + total / 100 else print total + cents total > 100? true print $ + total / 100 false print total + cents
Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=)
Logical Operators What if we wanted to test for multiple conditions? For example, what if we want to print the temperature if it s below 80 degrees and greater than 50 degrees? We use logical operators: if (temp < 80 && temp > 50) System.out.println(temp); Created by Emily Hill & Jerry Alan Fails
Logical Operators Boolean expressions can also use the following logical operators:! Logical NOT && Logical AND Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)
Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then!a is false; if a is false, then!a is true Logical expressions can be shown using a truth table: a!a true false false true
Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b is true if a or b or both are true, and false otherwise
Logical AND and Logical OR A truth table shows all possible true-false combinations of the terms Since && and each have two operands, there are four possible combinations of conditions a and b a b a && b a b true true true true true false false true false true false true false false false false
Boolean Expressions Write an expression that evaluates to true if an integer variable age represents the age of a teenager (age >= 13 && age <= 19)
Boolean Expressions Write a statement that prints out It s fun to be a teen if age represents the age of a teenager if (age >= 13 && age <= 19) System.out.println( It s fun to be a teen ); if (age > 12 && age < 20) System.out.println( It s fun to be a teen );
Short-Circuited Operators The processing of && and is short-circuited If the left operand is sufficient to determine the result, the right operand is not evaluated if (count!= 0 && total/count > MAX) System.out.println ("Testing."); This type of processing is commonly used to avoid divide by zero and null pointer exceptions
Quick Check What do the following statements do? if (total!= stock + warehouse) inventoryerror = true; Sets the boolean variable to true if the value of total is not equal to the sum of stock and warehouse if (found!done) System.out.println("Ok"); Prints "Ok" if found is true or done is false
Indentation Indentation is for the human reader, and is ignored by the compiler if (depth >= UPPER_LIMIT) delta = 100; else System.out.println("Reseting Delta"); delta = 0; Despite what the indentation implies, delta will be set to 0 no matter what "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding
Nested if Statements The statement executed as a result of an if or else clause could be another if statement Braces can be used to specify the if statement to which an else clause belongs An else clause is matched to the last unmatched if (no matter what the indentation implies)
Comparing Data Created by Emily Hill & Jerry Alan Fails
Comparing Float Values You might consider two floating point numbers to be "close enough" even if they aren't exactly equal Don t use == when comparing real numbers (float or double), use a tolerance: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); The tolerance could be set to any appropriate level, such as 0.000001 or even 0.01, depending on precision
Comparing Characters Characters can be compared like numbers, since internally they are encoded as numbers: For example: a + 1 => b A + 1 => B a == a => true Characters Unicode Values 0 9 48 through 57 A Z 65 through 90 a z 97 through 122
Comparing Strings Remember a String is an object in Java, so we cannot use relational operators (==, <, >, etc.) to compare strings (or objects) Instead, use the equals method: if (name1.equals(name2)) System.out.println ("Same name"); Or compareto. For example, a call to name1.compareto(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2
Comparing Objects When applied to objects, == returns true if the two references are aliases of each other The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate
Practice! Created by Emily Hill & Jerry Alan Fails
Part A: static methods tested in main Write a method that takes someone s age as input and returns true if they can vote but not drink beer. (Note that you must be 18 to vote and 21 to drink.) Test in main Write a method isvowel that takes a character as input and returns whether or not the letter is a vowel. Test in main Write a method isvowel like above but taking a String as input instead of a character. Test in main Created by Emily Hill & Jerry Alan Fails
Part B: Timer class Create a Timer class that counts down from n to 0 (where n is specified by the constructor, 5 by default for the default constructor) You will need 2 fields: n & time_left Write a tick method that decrements the time left if time left is greater than zero, otherwise it prints: You have no time left! Created by Emily Hill & Jerry Alan Fails
Homework Finish this lab Work on CodingBat Read Chapter 5 Created by Emily Hill & Jerry Alan Fails