30 likes | 98 Views
5-3 Nested If- Elses : Consider the following 3 ways to compute a students grade: 1 st if ( ave > = 90 ) grade = ‘A’; if ( ave > = 80 && ave < 90 ) grade = ‘B’; if ( ave > = 70 && ave < 80 ) grade = ‘C’; if ( ave > = 60 && ave < 70 )
E N D
5-3 Nested If-Elses: • Consider the following 3 ways to compute a students grade: • 1stif ( ave > = 90 ) grade = ‘A’; if ( ave > = 80 && ave < 90 ) grade = ‘B’; if ( ave > = 70 && ave < 80 ) grade = ‘C’; if ( ave > = 60 && ave < 70 ) grade = ‘D’; if ( aveave < 60 ) grade = ‘F’; //Thoughts? • 2ndif ( ave > = 90 ) grade = ‘A’; else if ( ave > = 80 && ave < 90 ) grade = ‘B’; else if ( ave > = 70 && ave < 80 ) grade = ‘C’; else if ( ave > = 60 && ave < 70 ) grade = ‘D’; else grade = ‘F’; //Any Improvements? • 3rdif ( ave > = 90 ) grade = ‘A’; else if ( ave > 79 ) //We already know what? grade = ‘B’; else if ( ave > = 69 ) //Likewise, we already know? grade = ‘C’; else if ( ave > = 59 ) grade = ‘D’; else grade = ‘F’; //Optimal
Trace the following: if ( a > 0 ) if( a % 2 = = 0 ) System.out.print(“1. When Here?”); else System.out.print(“2. When Here?”); else if ( a < 0 ) System.out.print(“3. When Here?”); else System.out.print(“4. When Here?”); • Rewrite using nested if-else statements: if ( a > 0 && b > 0 ) System.out.print(“Both True”); else System.out.print(“At Least 1 False”); 1. How about? if ( a > 0 ) if ( b > 0 ) System.out.print(“Both True”); else System.out.print(“When Here?”); 2. How about? if ( a > 0 ) if ( b > 0 ) System.out.print(“Both True”); else System.out.print(“When Here?”); else System.out.print(“When Here?”); 3. Are there any other scenarios?
Enumerated Types (Advanced Topic 5.3 p294): • Allows you to define a like outcomes that have common meaning. public class Calender { public enumDaysWeek { Sun, Mon, Tue, Wed, Thur, Fri, Sat }; private DaysWeek day; : if ( day = = DaysWeek.Sun ) System.out.print(“ Read Paper”); else if ( day = = DaysWeek.Mon ) System.out.print(“ Free Coffee at McDonalds!”); else if ( day = = DaysWeek.Tue ) System.out.print(“ Is it Friday yet?”); • Switch Statements – Checking single values: switch ( day ) { case DaysWeek.Sun: System.out.print(“ Sunday”); break; case DaysWeek.Mon: System.out.print(“ Monday”); break; case DaysWeek.Tue: System.out.print(“ Tuesday”); break; case DaysWeek.Wed: System.out.print(“ Wednesday”); break; case DaysWeek.Thur: System.out.print(“ Thursday”); break; case DaysWeek.Fri: System.out.print(“ Friday”); break; default: System.out.print(“ Weekend”); } • Homework: p219 R5.10, 5.13 p223 P 5.9