Class 8 M 2/6 Comp 110 Program 4 questions Branches ******************************* Quick Review Branches Simple Chained Nested Compound condition Examples: Simple branch if( x > 5 ) System.out.println("A"); Chained - one branch after another. if( x > 5 ) SOP("A"); if( x < 10 ) SOP("B"); or if( x > 5 ) SOP("A"); else SOP("C"); if( x < 10 ) SOP("B"); Nested - one branch inside another if( x > 5 ) { if( x > 10 ) SOP("A"); else SOP("B"); } Compound condition - more than one question asked if( x > 10 && x < 5) SOP("A"); else SOP("B"); ******************************* In-class exercise. Answers to 1 and 2 included. 1) What is displayed if x is a) 4 b) 5 c) 6 d) 9 e) 10 f) 11 i) if( x > 5 ) SOP("A"); else if( x < 10 ) SOP ("B"); else SOP("C"); ii) if( x > 5 ) { SOP("A"); if( x < 10 ) SOP("B"); } else SOP("C"); Answer: i) a)B b)B c)A d)A e)A f)A ii) a)C b)C c)A B (on 2 lines) d) A B (on 2 lines) e)A f)A 2) Write a fragment of code that will test whether an integer variable, score contains a valid test score. Valid test scores are in the range 0 to 100. Print valid or invalid. The code segments starts with Scanner keyboard = new Scanner(System.in); int x = keyboard.nextInt(); Write 3 separate versions of this code: a) Use nested if statements b) Use chained if statements c) Use a single if statement with a compound condition Answer a) if( x >= 0 ) if( x <= 100 ) SOP("valid"); else SOP("invalid"); else SOP("invalid"); b) if( x < 0 ) SOP("invalid"); if( x > 100 ) SOP("invalid"); else SOP("valid"); String result = "valid"; if( x < 0 ) result = "invalid"; if( x > 100 ) result = "invalid"; SOP( result ); c) if( x >= 0 && x <= 100 ) SOP("valid"); else SOP("invalid"); 3) What is the output from the following i) int x = 5; if( x >= 5 ) SOP("A"); SOP("B"); ii) int x = 5; if( x >= 5 ) SOP("A"); else SOP("B"); 4) 3) You are writing a program that asks the user to give a yes-or-no response. It will accept either "y" or "yes" as an affirmative response. Assume the program reads the user's response into a String variable called response. String response = keyboard.nextLine(); Why doesn't the following work? if( response.equals("yes" || "y") ) SOP("true"); if( response.equals("yes") || response.equals("y") ) 5) What is the value of each of the following boolean expressions if x=5 y=10 and z=15? a) ( x < 5 && y > x ) b) ( x < 5 || y > x) c) ( x > 3 || y < 10 && z == 15 ) d) ( ! (x > 3) && x != z || x + y == z) 6) The service charge for cashing a check depends on the amount of the check. If check amount , $10, charge $1. If check amount is greater than $10 but less than $100, charge 10% of the amount. If amount is greater than $100 but less than $1000, charge $5 + 5% of amount. If amount > $1000, charge $40 + 1% of amount. Given int amount = keyboard.nextInt(); Write if statements to print out the amount of the charge. Also, do you notice anything incomplete about this problem?