CMSC 131 Fall 2006Jan Plane (adapted from Bonnie Dorr)Lecture 17:Ternary Operator, Switch, Break, ContinueLast time:1.Example class development: Rational NumbersToday:1.ternary operator the ?: (conditional operator)2.switch3.breakCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)1The Conditional OperatorThe only ternary operator (has 3 operands)Format:boolean-expression?expression1:expression2Purpose:test to see if boolean-expression is true or falsewhole expression takes on the value of expression1 when boolean-expression was truewhole expression takes on the value of expression2 when boolean-expression was trueCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)2What is another way to write this if-else-if statement?if (grade == ‘A’)System.out.println (“I’m very happy”);else if (grade == ‘B’)System.out.println (“I’m relatively happy”);else if (grade == ‘C’)System.out.println (“At least I get credit”);elseSystem.out.println (“Check with the professor”);CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)3The switch Statement: General Formswitch ( control-expression ) {case case-label-1 :statement-sequence-1break;case case-label-2 :statement-sequence-2break;…case case-label-n :statement-sequence-nbreak;default :default-statement-sequencebreak;}Our text says it cannotbe a byte or short.This is wrong!The optional “default” case is executed if no other case matchesThe control-expression isone of the following types:char, int, short, byteEach case label must be a value intype of control expressionYou may have any number of statements,including if-else and loopsThe “break” statement jumpsout of the switch statementCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)4Case ContinuationThe control expression can have one of the following types: char, int, short, bytenot float, double, boolean, longnot a String or other object Case continuation also called “cascading case behavior”, “falling through to the next case”, etc.It is occasionally handy for combining of casese.g. case-insensitivityswitch (grade) {case ‘a’:case ‘A’:System.out.println (“I’m very happy”);break;…}Be very careful about using this cascading behavior!Always insert break statements after every caseThen remove ones you do not wantCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)5The default Casedefault is optionalIf omitted, and no case matches, then the switch statement does nothingHowever: you should always include a default case, even if you want nothing to be done if no case matches (you should never rely on implicit behavior!)Although cases are not required to be in order … (following is legal):switch ( option ) {case 2:…case 9:…default:…case 1:…}… it is much better to list cases: in increasing order with default lastCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)6Why Use switch?switch can also be implemented using if-elseswitch also restricted in terms of data types in control statementsIncluding break statements is a painHoweverswitch often more efficient (compiler generates better code)Code can be more compact because of case-continuation behaviorSometimes case analysis is clearer using switchCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)7More about break break can also be used to exit immediately from any loopwhiledo-whilefor e.g. “Read numbers from input until negative number encountered”Scanner sc = new Scanner (System.in);int n;while (true) {n = sc.nextInt ();if (n < 0)break;else<process n>;}Loop only terminates when break executedThis only happens when n < 0CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)8Warning about breakUndisciplined use of break can make loops impossible to understandTermination of loops without break can be understood purely by looking while, for partsWhen break included, arbitrary termination behavior can be introducedRule of thumb: use break only when loop condition is always true (i.e. break is only way to terminate loop)When you use it, make sure it has a good comment explaining what is happeningCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)9continue Statement continue can also be used to affect loopsbreak halts loopscontinue jumps to bottom of loop body Following prints even numbers between 0 and 10for (int i = 0; i <= 10; i++){if (i % 2 == 1)continue;System.out.println (i);}Effect of continue statement is to jump to bottom of loop immediately when iis oddThis bypasses println! continue should be avoidedConfusingEasy equivalents exist (e.g. if-else)Included in Java mainly for historical reasons When you use it, make sure it has a good comment explaining what is
View Full Document