DOC PREVIEW
UMD CMSC 131 - Lecture 6: If-Else-If and Loops

This preview shows page 1-2-22-23 out of 23 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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 indentationHowever, 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” ProblemWhich “if” an “else” is associated with can be ambiguous!Java rule: else is associated with “innermost”possible ifGood 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 ElsesA 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 ProjectsYou must use meaningful variable names and good indentation.Java convention indentingshowing the purposebraces in the correct places with respect to the linesJava convention of capitalization of identifiersFully blocked if statementsLines less than or equal to 80 columnsYou 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 ConventionsWhat is legal for variable names?Letters, digits, $, _Can’t start variable name with digitAvoid reserved wordsUse camelCase:Variables & Methods use lower-case for first letterClasses/Interfaces use upper-case for first letterCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)7Variable Name Conventions: ExamplesNaming 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 NamesChoose names for your variables to reflect their purposeBadString 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 JavaPrograms 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 onceSame prompt might be printed in several placesJava answer: named constantsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)10Named Constantsfinal int MAX_OK_TEMP = 99;Just like a regular variable declaration, except…Special term finalNecessity of initial valueAny variable name will work, but convention is to use all capitalsDifference with regular values: assignment attempt leads to error!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)11Examplesfinal 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 JavaSo far our programs execute every program statement at most onceOften, 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:whiledo-whileforWe 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 bodyA boolean conditionIdea: 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 LoopsLoops can run forever if condition never becomes falseBe careful when programming loops!Add statements for termination into loop body firstMake sure these statements are at end of bodye.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 ScopingVariables can


View Full Document

UMD CMSC 131 - Lecture 6: If-Else-If and Loops

Documents in this Course
Set #3

Set #3

7 pages

Exam #1

Exam #1

6 pages

Exam #1

Exam #1

6 pages

Notes

Notes

124 pages

Notes

Notes

124 pages

Load more
Download Lecture 6: If-Else-If and Loops
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 6: If-Else-If and Loops and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 6: If-Else-If and Loops 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?