1 / 46

Last Time

Last Time. Unary operators: Casting Boolean “NOT” Arithmetic operators Other Assignment operators Screen I/O (Console and simple GUI) Variable Scope if statements. Today. Reminder: Lab 1 and Assignment 1 are posted. Assn 1 is due one week from today at 7pm.

phepworth
Download Presentation

Last Time

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Last Time • Unary operators: • Casting • Boolean “NOT” • Arithmetic operators • Other Assignment operators • Screen I/O (Console and simple GUI) • Variable Scope • if statements CISC101 - Prof. McLeod

  2. Today • Reminder: Lab 1 and Assignment 1 are posted. • Assn 1 is due one week from today at 7pm. • Start out with a “warm-up” exercise! • Math class • Style and Documentation • Loops • More exercises! CISC101 - Prof. McLeod

  3. Exercise – An Easy One • Prompt the user for an integer. • Tell the user if the number is odd or even. CISC101 - Prof. McLeod

  4. Exercise – From Tuesday • Obtain an outdoor temperature (in degrees Centigrade) from the user. • If the temperature is less than -40, or greater than +40 tell him that the temperature is not legal and exit the program. • If the temperature is >= -40, but less than 0, display “It is cold! Wear a parka.”. • If the temperature is >= 0, but less than 15, display “It is cool. Wear a jacket.”. • If the temperature is >= 15 and less than 25, display “It is nice! Wear shorts.”. • If the temperatuer is >=25 and less than 40, display “It is hot! Seek the beach!”. CISC101 - Prof. McLeod

  5. The Math Class • Java’s standard mathematical methods are found in the Mathclass. They are invoked by naming the class name followed by the method name, separated by a period. For example, the sine of a value can be calculated as: double y = Math.sin(x); • The Math class methods are static, (like the methods in the System.out class). • This means you can call them directly (without instantiation). CISC101 - Prof. McLeod

  6. The Math Class – Cont. • To get more information on all the methods, look in the API documentation. CISC101 - Prof. McLeod

  7. Example: Math.random() Method • Provides a “pseudorandom” double value between 0 and 1.0 • How to calculate a random int value between 1 and 1,000, for example? int randVal = (int)(1000 * Math.random()) + 1; CISC101 - Prof. McLeod

  8. Programming Style & Documentation • Purpose is to make your code readable (and “debuggable”) by you or another programmer who is familiar with the Java language. • Internal style elements are documentation (comments), spacing, and descriptive variable names. • Select the conventions you want to use and be consistent. CISC101 - Prof. McLeod

  9. Programming Style & Documentation – Cont. • Comments: • Add a block comment to the top of the class and at the beginning of each method. Describe overall purpose of class/method, main algorithm used, author, date created, and any assumptions made and/or bugs found. Method comments should state what parameters are expected by the method and what the method returns. • Comments for variable declarations, when the name of variable is not self-explanatory. • Comments at the beginnings of logical blocks of code. • In-line comments to indicate the closing brackets of blocks and what they close. CISC101 - Prof. McLeod

  10. Programming Style & Documentation – Cont. • Spacing (alignment) • Class definition header starts at column 1, and closing bracket on column 1. • Indent of about 3 or 4 spaces is adequate. • Method headers and instance variable declarations indented once. • Code inside any block, including method code indented once from alignment of method header, or outer block. CISC101 - Prof. McLeod

  11. Programming Style & Documentation – Cont. • Opening “{“ can be at the end of a statement line, or on the line below. • Closing “}” on same column as the column where the method header is declared, or the statement containing the opening “{“. “}” is usually by itself on a line. • Add a comment after “}” to indicate what is being closed. • If you have an overlong line, it is OK to continue the line on the line below, but indent the continued part of the line. (Note – do not try to continue a line in the middle of a String literal!) CISC101 - Prof. McLeod

  12. Programming Style & Documentation – Cont. • Spacing (“white space”) • Add blank lines before and after methods and larger logical blocks. • One statement per line. (Longer statements can be broken onto multiple lines.) • Use a space before “{“, “(“ and “[“. Use a space after “)” and “]” (unless the next character is “;”). • No code after “{“ or “}” on same line. • No space after “(“ or before “)”. • Use space after “,” or “;” in parameter lists or for loop arguments, but not before. • Put a space on both sides of an binary operator. • No space before “;”. CISC101 - Prof. McLeod

  13. Programming Style & Documentation – Cont. • Variable Names • Also applies to method and class names. • Follow java restrictions on names: • Use only letters, numeric digits (0 to 9) and the “_” character. • Cannot start name with a number. • Java is case sensitive! • Variables and method names usually start with a lower case character. Class names start with an upper case character. Constants are all in upper case. • Variables are usually nouns. • Methods are verbs or verbs and nouns. CISC101 - Prof. McLeod

  14. Programming Style & Documentation – Cont. • Be descriptive, but not excessive! • Examples: • numStudents • setPassingGrade ( parameter_list ) • Somewhat too long…: • flagThatIsSetToTrueIfAProblemArisesWhenThereIsAFullMoonOverMyHouseInTheWinterWhileMyProgramIsRunning • It is OK to use single letter variable names such as i, j, k for counters in loops. CISC101 - Prof. McLeod

  15. Programming Style & Documentation – Cont. • The java compiler ignores all white space including space characters, tabs and carriage return/line feed characters. • Note that most java keywords are in lower case. • You will get an error message if you attempt to use a keyword as a variable name. CISC101 - Prof. McLeod

  16. Do public class StyleDemo { public static int someSum (int num1, int num2) { int sum = num1 + num2; return sum; } // end someSum method } // end StyleDemo class CISC101 - Prof. McLeod

  17. Don’t! public class StyleDemo{ public static int s(int l,int l1){ int S=l+l1; return S; }} CISC101 - Prof. McLeod

  18. Repetition or Using “Loops” • We will discuss: • while • do/while • for • The “for each” loop in Java 5.0 • Use of “break” and “continue” CISC101 - Prof. McLeod

  19. Repetition or “Loops” • Suppose we combine a boolean test with some kind of structure that allows us to branch back up to an earlier piece of code: if true if false etc. CISC101 - Prof. McLeod

  20. Repetition - Cont. • The boolean test determines when to stop the repetition - as long as the condition is true, the loop keeps going. • Something inside the looping part must affect what is tested in the condition - right? What if it did not - what would happen? CISC101 - Prof. McLeod

  21. Repetition - Cont. • A simple example - suppose we wanted a loop to execute only 20 times: i = 1 if true i < 21 if false i = i+1 etc. CISC101 - Prof. McLeod

  22. Repetition - Cont. • The number of repetitions is controlled by changing the limit value for the loop counter - “i” in the example on the previous slide. • That example had i increasing by one each time. The loop counter was being incremented by one. • It could have been incremented by some other value, 2, 3, or whatever. • You could use something like “i = i * 2” to increment the counter. • If the counter is decreased in value each time, it is being “decremented”. CISC101 - Prof. McLeod

  23. Repetition - Cont. • Suppose, in the previous example, i was decremented by one instead. What would happen? i = 1 if true i < 21 if false i = i - 1 etc. CISC101 - Prof. McLeod

  24. Repetition - Cont. • The dreaded “infinite loop”! • The java compiler will not prevent you from coding a loop like the one shown - it will compile, and it will run! • And run, and run,and run,and run,and run,and run, and run,and run, and run,and run… • As a programmer, you must be “on guard” for such logic errors in your code. CISC101 - Prof. McLeod

  25. Reminder - Increment and Decrement Operators • In loops, expressions like: j = j + 1; and k = k - 1; are used so often, it is typical to see the postincrement operator: j++; is the same as j = j + 1; k--; is the same as k = k - 1; • You can use either notation. CISC101 - Prof. McLeod

  26. “while” loop • A java while loop can be used to code the structure shown in the flowchart above (the “increment” one on slide 27): int i = 1; while (i < 21) { // other statements i = i + 1; // or you could use i++: } // end while • The “{ }” brackets enclose the statements that are repeated. • (A single statement to be repeated in the loop does not require the “{}”.) CISC101 - Prof. McLeod

  27. “while” loop - Cont. • Note that java (thank goodness!!!) does not have anything equivalent to a “goto” statement. • (And if it did, I would not tell you about it, anyways!!) • So, you cannot construct a loop with an “if” statement and a goto. • An “if” statement cannot give you repetition, it only allows you to decide on a single pass through a branch of code. CISC101 - Prof. McLeod

  28. “while” loop - Cont. • while loop syntax: while ( boolean_expression ) { block_of_code } • As long as boolean_expression evaluates to true the statements in the block_of_code continue to execute. • By mistake, you might write the following - what would happen? while ( boolean_expression ); { block_of_code } CISC101 - Prof. McLeod

  29. “while” loop - Cont. • The boolean expression tested in a while loop could be false to start with: int i = 40; while (i < 21) { // other statements i = i + 1; } • In this case, the loop would not execute at all. • Use a “do/while” loop if you need a loop that will always run at least once: CISC101 - Prof. McLeod

  30. “do/while” loop • Syntax: do { block_of_code } while ( boolean_expression ); • Note the “;” at the end of the while statement. • Since the conditional test is at the end of the loop, it will always execute the loop at least once. CISC101 - Prof. McLeod

  31. “do/while” loop - Cont. • For example, suppose we must obtain a value between 1 and 100, inclusive, from the user: int aVal = 0; // The compiler will force us to // initialize aVal do { System.out.print(“Enter value between 1 and 100:”); // code to obtain a value from the user } while (aVal < 1 || aVal > 100); • As long as the user does not do what he is told, the loop will continue to re-prompt him for the correct value. CISC101 - Prof. McLeod

  32. “for” loop • The kind of while loop shown above: int i = 1; while (i < 21) { // other statements i = i + 1; } is used so often, that Java has provided another looping structure that does all that is shown above, but needs only one line: for (int i = 1; i < 21; i = i + 1) { // other statements } CISC101 - Prof. McLeod

  33. “for” loop - Cont. • Or, as written with an increment operator: for (int i = 1; i < 21; i++) { // other statements } • Syntax: for (initialization;boolean_expression;update) { block_of_code } • for loops are used when you know, in advance, the number of repetitions desired. CISC101 - Prof. McLeod

  34. “for” loop - Cont. • You don’t have to declare the counter inside the for loop, if you have declared it earlier in your program. • But if you do declare it in the “for” statement then the scope of that variable will only be inside the loop block. CISC101 - Prof. McLeod

  35. “for each” Loop in Java 5.0 • Often, you will want to “visit” every element in a collection, not just a part. • Syntax of the “for each” loop: for (type_variable : collection) { // statements } • These loops are only used with collections. CISC101 - Prof. McLeod

  36. “for each” Loop in Java 5.0, Cont. • (We don’t know what arrays are yet, but just for now:) • For example, suppose we have an array called “data”, containing a collection of double type numbers, and you want to add them all up: double sum = 0; for (double e : data) { sum = sum + e; // or sum += e; } CISC101 - Prof. McLeod

  37. “for each” Loop in Java 5.0, Cont. • Equivalent normal “for” loop: double sum = 0; for (int i = 0; i < data.length; i++) { sum = sum + data[i]; //or sum += data[i]; } • The “for each” loop is a bit easier with arrays, but is even better suited for other kinds of collections. CISC101 - Prof. McLeod

  38. Loops - Misc. • Don’t declare variables inside loops, as the repeated declaration process uses up time and memory unnecessarily. • Loops are often nested - to usually not more than three levels. For example: int i, j; int sum = 0; for (i = 1; i <= 100; i++) for (j = 1; j <= 10; j++) sum++; • sum would be 1000. CISC101 - Prof. McLeod

  39. Loops - Misc. - Cont. • There is no limit in Java to how many levels you can nest loops. • It is customary, but not necessary, to use the variables i, j, k as loop counters. • Loops really demonstrate the strength of computers as they allow the machine to complete mind-numbingly boring tasks with perfect accuracy! • Loops will always be used with any file I/O and array operations. CISC101 - Prof. McLeod

  40. Other Java Keywords Used With Loops • break and continue • The continuestatement interrupts the execution of a loop, and returns control to the top of the loop. • The breakstatement interrupts the execution of a loop, and transfers control to the first statement after the loop. CISC101 - Prof. McLeod

  41. Use of “continue” • For example, • Would print: CISC101 - Prof. McLeod

  42. Use of “break” • For example, • Would print: Fall 2002 CISC121 - Prof. McLeod

  43. Use of “break” & “continue” • Only use these keywords when it makes your code easier to read. • Avoid the use of more than one break or continue inside a loop. • If you use a condition to issue a break statement, then why can’t you put that condition in the loop test? • Overuse of break statements can lead to “spaghetti” code - just like the use of “goto” statements! CISC101 - Prof. McLeod

  44. Loop Exercise 1 • Obtain from the user a positive upper limit. • Also obtain an increment value. • Print out all the numbers from 0 to the number before the upper limit using the increment, one number per line. For example, if the user supplies 50 and 20, the output would be: • Supply an error message if the input values are not legal. 0 20 40 CISC101 - Prof. McLeod

  45. Loop Exercise 2 • Obtain a positive integer number, > 1 from the user. If the number supplied is illegal, continue to prompt him until it is. • Print out all the numbers that divide this number evenly, including the number itself, starting from 2. For example, if the user supplies 10, the output would be: 2 5 10 CISC101 - Prof. McLeod

  46. Loop Exercise 3 • Prompt the user for a positive number of numbers. • If this number is > 0, display to the screen this many prime numbers, starting from 2. For example, if the user supplies 5, the output would be: 2 3 5 7 11 CISC101 - Prof. McLeod

More Related