CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG 1
Notice Prepare the Weekly Quiz The weekly quiz is for the knowledge we learned in the previous week (both the class on Tuesday and Thursday) Review the class quiz Review the class slides, especially the review part I will mark the important knowledge in red in the class slides Requests for the weekly quiz Open book, but no electronic devices allowed The first two weekly quiz are considered as practice, no impacting for your finial grading Assignments The Class 8 Exercise for today is posted here. The homework 2 and posted it here They are due this coming Sunday, at 11:59 PM. 2
Review The for loop In programming, we often do the same thing many times To make this possible programming languages provide loops The simplest kind of loop is the for loop Suppose you wanted to print the first 5 perfect squares We need to repeat something 5 times, changing a value each time 3
The for loop A for statement has two major parts Three statements inside parentheses that control the loop A series of statements executed with each pass through the loop The series of statements are called the loop body... and are enclosed in curly braces, { } Here is the format for the for loop for (INITIALIZATION; CONTINUATION_TEST; UPDATE) { } STATEMENT;... 4
The for loop The code inside the parentheses controls the loop It consists of three separate statements on the same line separated by semi- colon ; 5
The for loop Declare the variable Assign it its first value It s done before entering the loop An expression that returns a boolean value The loop will continue if the continuation test is true Otherwise, the loop will stop The update changes the value after the loop statements have been executed before the continuation test i is called control variable or loop variable It s used to count the number of pass trough the loop It must be an integer The traditional names for such variable is i, j, or k 6
The for loop in Action Here is the flow chart for a for loop Give the control variable its starting value This happens only once Evaluate the test condition If the test is true: Execute all statements. Then, update the control variable If the test is false, jump out of the loop 7
Common Programming Error: Forgetting Curly Braces One of the most common Java programming errors is forgetting to use curly braces The curly braces mark the beginning and end of the loop body The loop body is the series of statements... that are executed with each pass through the loop It prints Hi! 10 times and Ho! once 8
for Loop Patterns The three control statements in a for loop can be used many ways. But some patterns are more common than others The most common for loop pattern is the following for (int LOOP_VARIABLE = 1; LOOP_VARIABLE <= n; LOOP_VARIABLE++) { } STATEMENT;... This loop starts with the control variable set to 1 and executes the statements contained in the loop body n times So the following code will produce this output: 9
for Loop Patterns Often, it is more convenient to start counting from 0 instead of one Here is the pattern for (int LOOP_VARIABLE = 0; LOOP_VARIABLE < n; LOOP_VARIABLE++) { } STATEMENT;... There are two differences between this pattern and the previous one The control variable is initialized to 0 instead of 1 And the continuation test uses < instead of <= 10
for Loop Patterns Usually the update statement increases the value of the loop variable But you can also run a for loop backwards Here the the pattern for a decrementing loop for (int LOOP_VARIABLE = n; LOOP_VARIABLE >= 1; LOOP_VARIABLE- - ) { STATEMENT;... } 11
Nested for Loops The for loop executes one or more statements But the for loop is, itself, a statement That means you can have one for loop inside another for loop This is called a nested loop Here's an example Each loop has its own, distinct, loop variable It s easier to read nested loops from the inside out The innermost loop runs five times to print a message The outmost loop runs the innermost loop tem times Notice the control variable for each loop must be different 12
Nested for Loops One more example The inner loop prints the value of the control variable as it goes from 1 to 3 The output loop executes the inner loop 6 times The output is 13
New Material Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 14
Scope As programs get longer you have to be careful... that different part of the code do not conflict with each other One way programming languages deal with this problem... is using a concept call scope The scope of a an identifier is the part of the program where it can be used Scope applies to Variables Methods When an variable or method is outside its scope that the compiler does not know about it so it is invisible 15
Scope of Static Method The scope of a static method... is the entire class in which it appears So any static method can call any other static method... no matter which comes first... if they are in the same class They can also call static methods in other classes... but then they have to give the class name 16
Scope of Static Method In the following code, scope of the static method sayhello... is all the sections of the program shown in red 17
Scope of Variable The scope of variables is different In general, the scope of a variable starts where it is declared... and ends which the closing curly brace that encloses it The way to identify the scope of a variable is: find the pair of curly braces that directly encloses the variable declaration the scope is from the point where it s declared to the closing curly brace 18
Scope of Variable So in the in the code above the scope of the variable message is shown in light blue... The same variable name can be used in different methods without the compiler becoming confused A variable declared inside a method is called local variables It s a good programing practice to declare variables in the smallest scope possible. This is called localizing variables 19
Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 20
The Scope of for Loop Variable The general scope rule for variables does not work for loop variables The scope of a loop variable is The part of the code between the for loop curly braces And the part of the code between the parentheses that starts the loop So the scope of the loop variable i is 21
The Scope of for Loop Variable You will get a syntax error if the code is written as follows: 22
Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 23
Code Block The part of a Java program between an open curly brace, {... and the matching closing curly brace, }... is called a code block A code block is section of code that is surrounded... by a matched pair of curly braces, { } We can use the idea of a code block to describe the scope of a variable The scope of a variable starts with the line where it is declared... and continues to the end of the code block in which it is declared 24
Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 25
Pseudocode When you write more complex algorithms, it s hard to write the entire algorithm immediately One way to deal with this is to use pseudocode When we write pseudocode, we write steps to solve a problem in simple English Then we break down these steps into simpler steps We keep doing this until we have an English description of the steps that can then be translated into Java code 26
Pseudocode Suppose we wanted to write a program to print following triangle Our first crack at the pseudocode might look like this draw a downward pointing triangle of 5 lines using asterisks But if you think for a moment, you will realize that this is not enough The following figure is a downward pointing triangle but is not what we want 27
Pseudocode So let's refine our pseudocode: draw a downward facing triangle of 5 lines using asterisks with no space between them But the following triangle would also satisfy this description So let's try again draw a downward facing triangle of 5 lines using asterisks with no space between them and the downward sides are of equal length Up to now, we have just refined our description of what needs to be done This is an important first step 28
Pseudocode But now we have to start thinking about how we will describe this to the computer using actions it can perform It seems clear we will need a for loop, so let's start with that But each line is different Each line must print a different number of spaces before it prints the asterisks So we need to increase the number of spaces in each line starting with 0 So let's refine our pseudocode 29
Pseudocode But once we have the right number of spaces and asterisks... we need to go to the next line So let's try again The next step is to calculate the number of asterisks and spaces... needed for each line If we number the lines 1 through 5... we want the following values for each line 30
Pseudocode There is a simple algebraic relationship... between the line number... and the number of spaces and asterisks The number of spaces is equal to the line number minus 1 The number of asterisks is trickier Notice that the number of asterisks decreases by two with each line But what about the first line? If we add 2 to 9 we get 11 So if we start with 11... and subtract 2 at each line... we get the right number of asterisks for each line 31
Pseudocode Let's add this to the for loop in our pseudocode The lines to write asterisks and spaces each need a for loop 32
Pseudocode Translating this into Java, we get When we run this code we get 33
Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 34
Reusing Existing Code Sometimes the easiest way to write a program... is to modify some existing code Let's say you want to write a program to draw the following We might be able to use DrawDownwardTriangle.java instead If you look carefully, you will see that the 1st line of DrawDownwardTriangle... is the same as the 5th line of the figure we want... And so on 35
Reusing Existing Code So all we have to do to get the figure we want is change the direction of counting in the outer for loop of DrawDownwardTriangle In DrawDownwardTriangle.java the outer loop counted from 1 to 5 For this code, we want the outer loop to count from 5 to 1 Here is how we do it 36
Outline Scope The Scope of for Loop Variable Code Block Pseudocode Reusing Existing Code Class Constants 37
Class Constants For the code in DrawCone.java for ( int i = 1; i <= (11 - (2 * line_number)); i++) Someone reading the code for the first time might ask "Why 11?" Programmers call values like this magic numbers They make the program work but it is not clear how Magic numbers make for bad code Whenever we can, we should replace such numbers with an expression... and those expressions should use constants A constant is like a variable except its value cannot be changed 38
Class Constants When creating a constant, you must use the keyword final... using the following format final DATA_TYPE CONSTANT_NAME = VALUE; like this final inthours_in_a_day = 24; By convention, constant names are spelled using ALL_CAPITALS The best place to put a constant is inside the class but outside all the methods. Such constants are called class constants. That way they are available to all methods in the class. The format is like this: public static final DATA_TYPE CONSTANT_NAME = VALUE; 39
Class Constants So our new version of DrawCone will look like this Add the class constant NUMBER_OF_LINES Change from 5 to NUMBER_OF_LINES Add the variable stars and change the magic number 11 to the expression using the new constant Use the new variable stars in continuation test 40
Class 8 Quiz 1. What do you call the series of statements that are executed with each pass through the loop? the loop body 2. What is a code block? all the statements between an open curly brace and the corresponding closing curly brace 3. What is scope? the part of a code in which an identifier (name) has meaning 4. What is the scope of a method? the entire class in which it is defined 41
Class 8 Quiz 5. What is the scope of a variable that is not a loop variable? from where it is defined to the end of the code block in which it is defined 6. What is the scope of a loop variable? the parentheses after the keyword for as well as the loop body 7. What is a constant? a "variable" whose value never changes 8. What is the scope of a constant that is not a class constant? the same as a variable. From where it is defined to the end of the code block in which it is defined 42
Class 8 Quiz 9. What is the scope of a class constant? The entire class in which it is declared 10. Write the statement that declares the integer constant DAYS_IN_WEEK. public static final int DAYS_IN_WEEK = 7; 43
Weekly Quiz1 1. What must the name of the source code file for the Java class CountToTenbe? CountToTen.java 2. If you want to run a Java program from the command line, what must the source code file contain inside the class definition? a main method 3. What is the first line of a method called? method header 4. What is a method? a group of statements that performs a specific task 44
Weekly Quiz1 5. Write the Java statement that prints "Hello world!"? System.out.println("Hello world!"); 6. In the previous statement, what does Java call "Hello world!"? a string literal 7. Write the escape sequence for the Tab character? \t 8. Can you use a Java keyword as an identifier? no 45
Weekly Quiz1 9. Is 1st_try a valid Java identifier? no 10. Write a one line comment that contains the text "This is a one line comment" // This is a one line comment 46