CS2011 Introduction to Programming I Selections (I) Chengyu Sun California State University, Los Angeles
Mortgage Calculator Revisited The formula How do we include the case where monthly interests rate is 0? Check if the interest rate entered is 0, and based on the result, select different part of the program to execute.
What's Needed in a Programming Language Branch Statement Check if the interest rate entered is 0, and based on the result, select different part of the program to execute. Boolean Expression Boolean Value
Boolean Expressions Used to check a condition, and the result would be either true or false (i.e. boolean) For example: interestRate == 0 radius > 0
Relational Operators Notice the difference between = and == Name < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to != No equal to Notice the difference between = and == In Java, relational operators can only be used on numbers
Boolean Values and Variables boolean is a data type just like int and double There are only two possible boolean values: true and false Boolean variables can be use to store boolean values (usually the results of some condition checks) Example: SimpleBooleans.java
Example: Addition Quiz Generate two random numbers between 0 and 10 Ask the user to enter the sum of the two numbers Display true or false depending on whether the answer is correct Use java.util.Random to generate the random numbers
Branch Statements if statement condition if-else statement condition true condition if-else statement true condition false
if statement if ( boolean-expression ) { statement(s); } If the boolean expression evaluates to true, execute the statement(s) in {} {} can be omitted if there's only one statement
If-else statement if ( boolean-expression ) { statement(s); } else { If the boolean expression evaluates to true, execute the statement(s) in {} after if (a.k.a. the if block), otherwise execute the statements in {} after else (a.k.a. the else block) {} can be omitted if there's only one statement in the block
Examples Modify Addition Quiz so it display correct/incorrect instead of true/false Use if statement Use if-else statement Modify Mortgage Calculator to handle the case where the interest rate is 0
Check Multiple Conditions Example: LetterGrade.java Conditions Letter Grade score >= 90 A 80 <= score < 90 B 70 <= score < 80 C 60 <= score < 70 D score < 60 F
Use Nested if-else Statements Write proper conditions Understand that certain conditions are already met when we get to the else block Use proper syntax else{ if(){ } else if(){ } else{