CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)Lecture 6:If-Else-If and LoopsLast time:1.Finish Scanner2.if statementsToday:1.More on if 2.Project assigned3.Named constants in Java4.LoopsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)1Nested If/Elses can be Ugly and Confusing!Too many lines with only one { } Easy to get lost in indentationHowever, we can use Java’s “innermost if”rule for elses to program more clearly!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)2The “Dangling Else” ProblemWhich “if” an “else” is associated with can be ambiguous!Java rule: else is associated with “innermost”possible ifGood programming practice: when in doubt, use { … }WE WILL USE { … } FOR ALL IF, IF-ELSE, IF-ELSE-IF, STATEMENTSCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)3Cascading ElsesA common programming paradigm:“if something is true, do one thing”“otherwise, if something else is true, do another thing”“otherwise, if something else entirely is true, do yet another thing”“otherwise, take a default action”How might we program this?CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)4A Common Programming Idiom“Idiom” = “convention”if (C1){S1;} else if (C2) {S2;…} else {Sn;}Note indentation and curly bracket conventions!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)5In ProjectsYou must use meaningful variable names and good indentation.Java convention indentingshowing the purposebraces in the correct places with respect to the linesJava convention of capitalization of identifiersFully blocked if statementsLines less than or equal to 80 columnsYou must use "named constants" for any literal values that will not change during program execution.CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)6Variable Name ConventionsWhat is legal for variable names?Letters, digits, $, _Can’t start variable name with digitAvoid reserved wordsUse camelCase:Variables & Methods use lower-case for first letterClasses/Interfaces use upper-case for first letterCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)7Variable Name Conventions: ExamplesNaming Conventions: Standards developed over time.Variables and methods: Start with lowercase, and use uppercase for each new word:dataList2 myFavoriteMartian showMeTheMoneyClass names: Start with uppercase and uppercase for each new word:String JOptionPane MyFavoriteClassNamed constants (variables whose value never changes): All uppercase with underscores between words:MAX_LENGTH DAYS_PER_WEEK BOILING_POINT Make variable names not too long, not too short Bad: crtItm Bad: theCurrentItemBeingProcessed Good: currentItemCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)8Meaningful Variable NamesChoose names for your variables to reflect their purposeBadString string = “”;System.out.println (“Enter name: “);string = sc.next();if (string.equals (“John Doe”)) …GoodString name = “”;System.out.println (“Enter name: “);name = sc.next();if (name.equals (“John Doe”)) …CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)9Named Constants in JavaPrograms often contain literals (= values)e.g.if (temp >= 97 && temp <= 99) …e.g.System.out.print (“Enter integer: “);If same value should be used in several places, how to ensure consistency?Check on temperature may be performed more than onceSame prompt might be printed in several placesJava answer: named constantsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)10Named Constantsfinal int MAX_OK_TEMP = 99;Just like a regular variable declaration, except…Special term finalNecessity of initial valueAny variable name will work, but convention is to use all capitalsDifference with regular values: assignment attempt leads to error!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)11Examplesfinal int MIN_OK_TEMP = 97;final int MAX_OK_TEMP = 99;…if (temp >= MIN_OK_TEMP && temp <= MAX_OK_TEMP) …final String INT_PROMPT = “Enter integer: “;…System.out.print (INT_PROMPT);CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)12Loops in JavaSo far our programs execute every program statement at most onceOften, we want to perform operations more than once:“Sum all numbers from 1 to 10”“Repeatedly prompt user for input”Loops allow statements to be executed multiple times. Loop types in Java:whiledo-whileforWe will study while, do-while now, for-loop laterCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)13while and do-while Loops while and do-while loops contain:A statement, called the bodyA boolean conditionIdea: the body is executed as long as the condition is true while-loop: The condition is tested before each body executionwhile( 〈〈〈〈condition〉〉〉〉 ){〈〈〈〈body〉〉〉〉} do-while-loop: The condition is tested after each body executiondo{〈〈〈〈body〉〉〉〉} while ( 〈〈〈〈condition〉〉〉〉 ); Main difference: do-while loop bodies always executed at least once because it is “bottom tested” rather than “top tested”CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)14Example 11public class Example11 {public static void main(String[] args) {int i = 1;while (i <= 10) {System.out.println(i);i = i + 1;}}}Increment of loop counter ensuresprogress toward loop termination“Loop counter”CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)15Infinite LoopsLoops can run forever if condition never becomes falseBe careful when programming loops!Add statements for termination into loop body firstMake sure these statements are at end of bodye.g.while (i <= 10) {System.out.println(i);i = i + 1;}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)16Example 11b: Lots of Loopingpublic class Example11b {public static void main(String[] args) {int i = 1;long total = 0;while (i <= 1000000) {total = total + i;i = i + 1;}System.out.println("Total is: " + total);}}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)17Example 12: do-whilepublic class Example12 {public static void main(String[] args) {int i = 1;do {System.out.println(i);i = i + 1;} while(i <= 10);}}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)18Variables, Blocks and ScopingVariables can
View Full Document