// Simple program to show how an if- statement works. import java.io.*; Lecture 6 class If { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader( System.in)); public static void main (String[] args) throws IOException { int age; Nested if s reprise. // output initial message System.out.print("Please enter your age: "); The boolean data type. More complex selection statements: switch. // input age age = new Integer(keyboard.readLine()).intValue(); Examples. Material from Holmes Chapter 3 (final part). // computation System.out.print("Here is your drink! "); if (age > 17) System.out.println("<whisky>"); System.out.println("<milk>"); 1 2-1 Drinking Last time we saw a simple example of a program involving conditionals. 1. output Please enter your age: ; 2. input age; 3. if (age 17) 4. output Here s your drink! 5. 6. output Here s your drink! whisky milk Nested if The statement that follows the conditional expression or the keyword can also be an if- statement. The resulting instruction is a nested if statement. Example. An automated vending machine gives you a glass of whisky if your age is right and you have the exact money! 2 3
milk milk // Simple program to show how nested if- statements works. import java.io.*; Reuse class If2 { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader( System.in)); What do we need to change here? public static void main (String[] args) throws IOException { int age, money; 1. output Please enter your age: ; 2. input age; 3. if (age 17) 4. output Here s your drink! whisky // output initial message System.out.print("Please enter your age: "); // input age age = new Integer(keyboard.readLine()).intValue(); 5. 6. output Here s your drink! 4 5-1 Pseudocode 1. output Please enter your age: ; 2. input age; 3. if (age 17) 4. if (money 50) 5. output Here s your drink! 6. 7. output a farewell message! 8. 9. if (money 30) 10. output Here s your drink! 11. 12. output a farewell message! whisky // computation if (age > 17) { System.out.print("Please enter the money (50p): "); money = new Integer(keyboard.readLine()).intValue(); if (money == 50) System.out.println("Here is your drink! <whisky>"); System.out.print("Sorry! No drink! You gave me too "); if (money > 50) System.out.println("much money!"); System.out.println("little money!"); { System.out.print("Please enter the money (30p): "); money = new Integer(keyboard.readLine()).intValue(); if (money == 30) System.out.println("Here is your drink! <milk>"); System.out.print("Sorry! No drink! You gave me too "); if (money > 30) System.out.println("much money!"); System.out.println("little money!"); 5 5-2
Remarks Pitfall with nested statements: can you spot the mistake in this example? One loses the first branch. Indentation! But do not over-indent! Boolean Expressions We have looked at relational operators last time. One can do calculations with booleans exactly in the same way as one can do calculations with numbers. - 12 34214 + 51 2367*(-85131)!false false true true && (!false)! is the logical negation, && is the logical conjunction and the logical disjunction.!(4 < a) (a <= 12) (a % 2 == 0) (0 <= a) && (a <= 9) 6 8 Primitive Data Type 4 Type Booleans Values false and true. Keyword boolean. Operators false, true Relational operators (producing a boolean value): <, >, ==,!=, <=, >=. Boolean operators (composing boolean values):!, &&,. Precedence: boolean operators have lower priority than arithmetic and relational ones (but higher than the assignment).. Boolean operators tables A B!A A && B A B true true false true true true false false false true false true true false true false false true false false Boolean expressions are used in the conditions of a selection statement and in loops (next week). 7 9
Switch If a selection is based on the values of some expression, belonging to an ordinal type then a switch statement may be used instead of a nested if-. Syntax. General format of a switch statement. switch ( expression ) case constant-expression : statements case constant-expression : statements... default : statements Exiting from a switch: the last statement executed in each case must be a break statement, otherwise Java would go sequentially to evaluate next condition. Problem Analysis. The validation of the date has a three-part solution. The first part is to validate a month as an integer in the range If the month is treated as an ordinal value of a switch expression, with case labels occurring for each of the twelve months, then should a month not be in the range 1 to 12, the error can be trapped as the default value. The second part involves the calculation of a leap year, and will only be considered if the month happens to be February. This calculation uses the following rules: if the year is evenly divisible by 4 and the year is not a century or the year is a century that is divisible by 400 then the year is a leap year! The third part of the solution involves the calculation of the number of days in a month.. 10 12 Algorithm. Case Study: Validation of Dates including Leap Years Problem. We want to write a program that validates a date. The format of the date MMDDYYYY is a single integer representing month, day and year. The single integer is split into individual integers representing MM, DD and YYYY. The program checks that the number of months in a year should not exceed 12, and that the number of days in each month has not been exceeded. The program also reports on leap years. 1. input the date 2. split the date into month, day and year?? 3. calculate the number of days in the month 1, 3, 5, 7, 8, 10, 12 numberofdays = 31; 4, 6, 9, 11 numberofdays = 30; 2 if it is a leap year then numberofdays = 29; numberofdays = 28; 4. output results (reporting errors...) 11 13
// chap_3\ex_9.java // program to validate a date in the format MMDDYYYY import java.io.*; class Ex_9 { static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); public static void main(string[] args) throws IOException { int date; int month, day, year; int numberofdays = 0; boolean error = false; // output results if (month == 2 && numberofdays == 29) System.out.println(year + " is a Leap Year"); if (day > numberofdays error) System.out.println("DATA ERROR - check day or month"); System.out.println("Date checked and is valid"); // input date in format MMDDYYYY System.out.println("Input a date in the format MMDDYYYY"); date = new Integer(keyboard.readLine()).intValue(); // split up date into MM DD and YYYY month = date / 1000000; day = (date % 1000000) / 10000; year = (date % 10000); 13-1 13-3 // calculate number of days in month switch(month) { // test for Jan, Mar, May, Jul, Aug, Oct, Dec case 1: case 3: case 5: case 7: case 8: case 10: case 12: numberofdays = 31; break; // test for Apr, Jun, Sep, Nov case 4: case 6: case 9: case 11: numberofdays = 30; break; // test for Feb being a Leap Year case 2: if (((year%4 == 0) && (year%100!= 0)) (year%400 == 0)) numberofdays = 29; numberofdays = 28; break; default: error = true; 13-2 Warm-up exercise Determine the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9. if ( x < 10 ) if ( y > 10 ) System.out.println("*********"); System.out.println("#########"); System.out.println("$$$$$$$$$"); if ( x < 10 ) { if ( y > 10 ) System.out.println("*********"); { System.out.println("#########"); System.out.println("$$$$$$$$$"); 14
!#"$ % &'( +*), -. / Mortgages Problem. A bank asks you to write a program that computes mortgage payments. From an interview with the bank director you learn that mortgages can be for 10, 15, 20 or 25 years only and that interest rates are different depending on the length of the repayment period. There is an (annual) 7.25% interest over 10 years, 8.5% over 15 years, 9.2% over 20 years and a 9.35% over 25 years. The program should let the user enter the number of years, and the loan amount. Then it will compute the monthly payment as follows: Tutorial Code the mortgage repayment calculator. Modify the drink vending machine program so that if the user input more money than needed for a given choice, the machine returns the chosen drink and a number of coins as the appropriate change. Assume that the amount of money entered is always given in pence, and that the vending machine has an infinite amount of one, five, ten, twenty and fifty pence coins. (Hint: use your solution to Holmes exercise 2.30). 15 17 Program Design 0Problem analysis. Studying the nature of the problem. Define input and output. 0Algorithm. (This is the creative step) Invent a way to solve it. 0Data Dictionary. List the data you need. 0Desk Check. Using traces, check the correctness of your program. 0Screen Layout. Decide how the output should look. 0Coding. Type in your program. 0Test results. After successful compilation, check that you get correct results. 16