Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal
Lesson Goals Understand Control Structures Understand how to control the flow of a program via selection mechanisms Understand if, if-else and switch statements Build programs with nested layers of decision making Building blocks of execution code Understand how to deal with the dangling else Understand else-if and how it is different from switch Understand the conditional operator 2
Control Structures in Java There are three control structures in Java Sequence Structure Built into Java Ensures that statements execute one after the other in the order they are written, unless directed otherwise Selection Structure (Chapter 4) Based on truth or falsity In Java includes the if, if else, if... else if, and switch statements Repetition Structure (Chapter 5) Allows for repetition of the same group of statements multiple times, as long as a condition is met In Java includes the do, do while, for, and enhanced for statements Also known as iteration statements or looping statements 3
Two Way Decisions Windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made. Start at the top of the chart then follow the line to the question: is it raining? The answer is either true or false. If the answer is true, follow the line labeled True, perform the instructions in the box "wipers on", follow the line to "continue". If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off", follow the line to "continue". The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made by executing many small decisions. 4
The Basic Syntax of the if Statement if (boolean expression) statement 1; statement 2; o 0 o statement n; The statements inside the block (delineated by a pair of braces) are executed only if the boolean statement is true You should use the braces even if there is only a single statement inside the block even though this isn t required No semicolon on the if statement An if with a single statement following it does not require curly braces, however, it us best to use them all the time at first if (boolean expression) statement 1; 5
Basic Terminology An if statement is also called a conditional or selection statement The phrase if (boolean expression) is called the if clause The boolean expression itself is called the condition The statements inside the curly braces comprise a block You can nest if statements inside each other 6
A Very Simple Example public class SimpleIfStatementDemo1 public static void main(string args[]) //Declaring a variable "test" and initializing it with a value 10 int test = 10; //Checking if "test" is greater than 5 if (test > 5) //This block will be executed only if "test" is greater than 5 System.out.println("Success"); //The if block ends. System.out.println("Executed successfully"); 7
The Basic Syntax of the if-else Statement Similar to the if statement, but exclusively executes an alternative set of statement(s) if the conditional is false if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 o statement n; else statement a; statement b; o 0 o statement x; Note: Once again if there is only a single statement then braces are not required if (boolean expression) // always evaluates to either true or false statement 1; else statement a; 8
A Simple Example of if-else import java.util.scanner; class NumberTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); int num; System.out.println("Enter an integer:"); num = keyboard.nextint(); if ( num < 0 ) System.out.println("The number " + num + " is negative"); num = num +5; else System.out.println("The number " + num + " is zero or positive"); num = num -4; System.out.println("The number is now " + num ); System.out.println("Good-bye for now"); 9
if else if Syntax Allows for testing for multiple different conditions Only the first case that tests as true will be executed If there is no else statement at the end there may not be execution of any of the blocks if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 statement n; else if(boolean expression) // always evaluates to true or false statement a; statement b; o 0 statement x; else //optional statement a; statement b; o 0 statement x; 10
An else if Example //This program assigns a letter grade based on a character grade import java.util.scanner; class IfElseDemo public static void main(string[] args) Scanner keyboard = new Scanner(System.in); System.out.println("Enter the grade"); int testscore = keyboard.nextint(); char grade; if (testscore >= 90) grade = 'A'; else if (testscore >= 80) grade = 'B'; else if (testscore >= 70) grade = 'C'; else if (testscore >= 60) grade = 'D'; else grade = 'F'; System.out.println("Grade = " + grade); Note: If you reverse the order then you would need to compare from bottom to top using <= Be careful in use of > vs. >=, etc. 11
A Note On boolean Expressions Be careful when using float or double type variables in boolean expressions Since there is always limited precision the possibility of an execution error exists, especially after more complex mathematical operations Example: (7.13*2.9)/(3.6*2.95) may be different than (7.13/(3.6*2.95))*2.9 See DecimalCompare.java 12
The Dangling if (1) Rule - An else matches with the nearest, previous, unmatched if that's not in a block. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.println( "aaa" ) ; else // Matches with previous unmatched if System.out.println( "bbb" ) ; In the example above, the else is indented with the inner if statement. It prints "bbb" only if num > 0 and num >= 10, which means it prints only if num is 10 or greater. In the example below, the else is indented with the outer if statement. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.println( "aaa" ) ; else // Matches with previous unmatched if System.out.println( "bbb" ) ; Which one does else match with? It picks the closest if unless there is a further clarification with the use of braces. This phenomenon of having to pick between one of two possible if statements is called the dangling else. Depending on which if the else is paired with, you can get different results. By now, you should know that Java doesn't pay attention to indentation. So both examples above are the same to Java, which means that it makes its determination based strictly on the syntax. To the Java Compiler there is no ambiguity (You can t say That s not what I really meant ) The compiler doesn t care about indenting. But you should for clarity 13
The Dangling if (2) What if we wanted the else to match with the first if? Then, we need braces. if ( num > 0 ) // Previous unmatched if if ( num < 10 ) // Unmatched, but in block System.out.println( "aaa" ) ; else // Matches with previous unmatched if not in block System.out.println( "bbb" ) ; //This prints if num <= 0. The else above matches with the previous, unmatched if not in a block. This happens to be the outer if. There is an unmatched if that's the inner if, but that's in a block, so you can't match to it. Notice the else sits outside of the block. An else can not match to a previous if if the else is outside the block, where the closest if is found. 14
The Dangling if The Rules Summarized Every else must match with a unique if. You can't have two or more else matching to the same if. If there is no matching if for an else, then your program won't compile. Each else must be preceded by a valid if Fortunately, your program fails to compile if you don't do this. Use Braces If you always use a block for if body and else body, then you can avoid confusion. However, it's useful to know the correct rules. 15
The switch Statement The syntax of a switch statement looks like: switch ( expr ) case literal1: case literal1 body case literal2: case literal2 body case literal3: case literal3 body default: default body Unlike if statements which contain a condition in the parentheses, switch contains an expression. This expression must be type int, char or String. (Note: String is a newer feature, and the book says only int or char) The semantics of switch are: Evaluate the expression Begin looking at each case, starting top to bottom If the value of the expression matches the case, then run the body Note: The case keyword has to be followed by a literal or a constant expression. It can't be a range or something that tests If you run a break statement, you then exit the switch If you don't run a break statement, and you are at the end of a body, run the next body. Keep running bodies until you exit If no match is made to the cases, run the default, if it exists. The default case is always run last, no matter where it appears. (It should be placed last, though). It is not mandatory to have a default statement. 16
Examples of the Switch Statement int x = 4 ; switch ( x ) case 2: System.out.println( "TWO" ) ; break ; case 4: System.out.println( "FOUR" ) ; break ; case 6: System.out.println( "SIX" ) ; break ; default: System.out.println( "DEFAULT" ) ; This evaluates x to 4. It skips case 2 since the value 4 doesn't match 2. It does match case 4. It runs the body and prints FOUR". Then it runs break and exits the switch. 17
Examples of the Switch Statement (2) Most of the times, you will end each case with break. Both C and languages like Java force you to write a statement that should be there all the time. Let's see what happens when you leave it out. int x = 4 ; switch ( x ) case 2: System.out.println( "TWO" ) ; case 4: System.out.println( "FOUR" ) ; case 6: System.out.println( "SIX" ) ; default: System.out.println( "DEFAULT" ) ; This prints out: FOUR SIX DEFAULT That's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case. However, there are cases where you will want to execute multiple statements from multiple cases (see next example) 18
Examples of the Switch Statement (3) You can combine cases together. int x = 4 ; switch ( x ) case 1: case 3: case 5: System.out.println( "ODD" ) ; break ; case 2: case 4: case 6: System.out.println( "EVEN" ) ; break ; default: System.out.println( "DEFAULT" ) ; 19
A Few Addi%onal Notes On the switch Statement Every switch statement can be implemented as an if/if else type statement It doesn t always work the other way around Obviously if the if/else is doing more complex comparisons (i.e. >=) or using floating point numbers, then this can t be implemented in a switch statement 20
The Condi%onal Operator (1) The conditional operator is used like this: true-or-false-condition? value-if-true : value-if-false Here is how it works: The true-or-false-condition evaluates to true or false. That value selects one choice: If the true-or-false-condition is true, then evaluate the expression between? and : If the true-or-false-condition is false, then evaluate the expression between : and the end. The result of evaluation is the value of the entire conditional expression. This approach can be used in assignment statements 21
The Condi%onal Operator (2) int a = 7, b = 21; System.out.println( "The min is: " + (a < b? a : b ) ); The output would be: The min is 7 22
The Condi%onal Operator (3) double value = -34.569; double absvalue; absvalue = (value < 0 )? -value : value ; ------------- ------ The constant value +34.569 is assigned to absvalue 23
An Example Using String Features That Will Be Taught Later import java.util.scanner; class RainTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); String answer; System.out.print("Is it raining? (Y or N): "); answer = keyboard.nextline(); if ( answer.equals("y") ) // is answer exactly "Y"? System.out.println("Wipers On"); // true branch else System.out.println("Wipers Off"); // false branch 24
Now That Your Programs Are GeWng More Complex Always check your programs through each of the else cases, switch gates etc. To do this you need to develop a set of test cases A test case has components that describe an input, action or event and an expected response, to determine if a feature of an application is working correctly Your test cases must be expansive enough to cover the full range of possibilities For instance if there is a statement if (x>4) you don t need to test for every possibility greater than 4, but you need to test for at least one. Typically we build a software test verification matrix 25
Sample Test Matrix Y 2 3 4 X 1 R1 R2 R3 2 R4 R5 R6 5 R7 R8 R9 7 R10 R11 R12 Test for all possible combinations When there are multiple variables break the testing into smaller pieces Always test for different and outlying conditions Positive, zero and negative numbers First and last number and some element in the middle when processing a list 26
Special Topic - Rounding Java includes different methods and techniques for rounding, some of which we will learn later this year However, if you are interested in rounding do the following: 1. Take the floating point number and multiply by 1000; Cast the number multiplied by 1000 as an int (if it is not too large for an int, otherwise use long 2. Take the original floating point number and multiply by 100; Cast the number multiplied by 100 as an int (if it is not too large for an int, otherwise use long 3. Determine if the last digit of the int value multiplied by 1000 is greater than or equal to 5 4. If the last digit is greater than or equal to 5 divide by 100.0 and add 1, otherwise divide by 100 Example: double x = 123.45678, xround; int xintthous = (int)(x*1000);// this is 123456 int xinthund = (int)(x*100);// this is 12345 if (xintthous%10 >=5) xround = (xinthund+1)/100.; else xround = (xinthund/100.); See full program in RoundingExample.java 27
Programming Exercises Class (1) Exercise 1. Sort Three Write a program that accepts three integers and displays the number in order from lowest to highest. 28
Programming Exercises Class (2) Exercise 8. Toll Free Numbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not. 29
Programming Exercises Lab (1) Exercise 3. Positive Sum Write a program that prompts for five integers and calculates the sum of those that are positive. 30
Programming Exercises Lab (2) Exercise11. Grade Conversion A certain school assigns number grades ranging from 0-100. Write a program that queries the user for a numerical score and converts the score to a letter grade according to thee following criteria: 0-59:F; 60-69 D: 70-72, C-: 73-76, C: 77-79 C+; 80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A; 97-100 A+ 31