Professional Documents
Culture Documents
LOOPS
The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds of loops: the while loop, the do-while loop, and the for loop.
The while(Boolean expression) is the loop header. It consists of the keyword while and a parenthesized boolean expression, often called the loop continuation expression. The body of the loop follows the header. The body of the loop is the statement or block of statements that are to be repeated as long as the loop continuation expression evaluates to true.
3
The braces are not necessary if the body of the loop is a single statement. Notice that there is no semicolon after the loop continuation expression. A complete while statement includes a loop header and the loop body.
When execution reaches a while statement, the parenthesized loop continuation expression is evaluated, if the expression is true the statement(s) that make up the body are executed and then execution returns to the evaluation of the continuation expression. This process is repeated until the loop continuation expression is evaluated and has the value false. When this happens execution continues with the statement following the while statement.
6
One repetition of the body of a loop is called an iteration. The while loop is a pretest loop. The continuation expression is tested before the body of the loop is executed. If the continuation expression is false on the initial test, the body of the loop is never executed, i.e. it never iterates.
False
Statement(s)
10
The key word do is followed by the body of the loop, the key word while, the parenthesized loop continuation expression, and a semicolon. The braces are not necessary if the body of the loop is a single statement.
11
12
When execution reaches a do-while statement, the statement or block of statements that make up the body of the loop are executed and then the continuation expression is evaluated. If the continuation expression evaluates to true execution continues at the first statement of the loop body. This process is repeated until the evaluation of the continuation expression results in the value false. When the continuation expression evaluates to false, execution continues with the first statement following the do-while statement. 13
The do-while loop is a posttest loop. The test expression is evaluated at the end of an iteration of the loop body. The body of the do-while loop is executed at least once.
14
Statement(s)
True
15
The for(initialization; Boolean expression; update) is the loop header. It consists of the key word for followed by three parenthesized expressions separated by semicolons. Notice there is not a semicolon after the third expression, the update.
17
The first expression is the initialization expression. It is typically used to initialize a counter, accumulator, or other variable that must be given a starting value. This is the first action performed by the loop and it is only done once.
18
The second expression is the loop continuation expression. This is a boolean expression that gets evaluated before every iteration of the loop to determine if the loop should iterate. If the continuation expression is true the statement(s) that make up the body of the loop are executed.
19
The third expression is the update expression. It is executed at the end of each iteration before execution returns to the continuation expression. Typically, this is a statement that updates the value of a variable that is used to control the loop.
20
There is no semicolon here. A complete for statement includes the statement(s) to be repeatedly executed.
The statement(s) in the loop body are to be repeated as long as the continuation expression evaluates to true. The braces are not necessary if the body of the loop is a single statement. Notice that there is no semicolon after the parenthesized expressions. A complete for loop/statement includes the loop body.
21
22
The for loop is a pretest loop. If the continuation expression evaluates to false on the initial test, the body of the loop does not iterate.
23
False
Statement(s)
Update
24
25
26
or
a += 1; b = 1;
27
28
29
(a + b)++;
30
Output:
x is 6 y is 9
32
Output:
a is 11 and b is 10
33
35
Problem: Write a pseudocode algorithm for a program that gets fifty grades from the user and calculates and displays the average of the grades entered. You may assume that the grades entered will all be whole numbers.
Set total to 0 For count of grades 1 through 50 Get the grade Add the grade to the total Calculate the average grade by dividing total by 50 Display the average grade
36
37
*** See Other Forms of the Update Expression in Section 4.5 of the text *** See Checkpoint questions 4.9c, 4.11, & 4.12 on pages 198199 of the text
38
COUNT_CONTROLLED LOOPS
All of the loops we have looked at so far are count-controlled loops. A count-controlled loop is a loop that executes a specified number of times. When you construct a count-controlled loop you need to: 1. Give the counter a starting value. 2. Compare the counter to a maximum (or minimum) value in the loop continuation expression. When the counter reaches this value the loop terminates. 3. Update the value of counter. Review the programs and see if you can figure out which variable is the counter and see how the three actions above were 39 done.
SENTINEL-CONTROLLED LOOPS
Suppose we did not know the number of grades that were to be entered in our application to calculate the average of the grades entered. Maybe the program is to be used for classes of varying sizes. It may be possible to solve the problem by using a sentinelcontrolled loop instead of a count-controlled loop. A sentinel is a special value, outside the range of expected inputs, which is used to signal that there is no more data to be entered. A sentinel-controlled loop continues to iterate as long as the sentinel value has not been read.
41
This version of our program to calculate the average of the grades entered by the user works for any number of grades greater than one. Since a do-while loop is used for the repetition, the body of the loop is executed once before the continuation expression is evaluated. This is ok as long as it is reasonable to expect that there is at least one grade.
43
44
45
NESTED LOOPS
There are no restrictions on what statements can be inside the body of a loop. Therefore, it is possible to have a loop inside a loop. We call this nesting of loops. In the program AvgOfGradesWInputValid.java, we have two while loops inside the body of a do-while loop.
46
NESTED LOOPS
47
Problem: Suppose we wanted to calculate and display the annual income for each of a companys three divisions and the annual income for the company as a whole from the monthly incomes of each division which are entered by the user.
48
Pseudocode for IncomeByDivision.java Assign the value 0 to the companys annual income For each division from 1 to 3 Assign the value 0 to the annual income for the division For each month from 1 to 12 Get the current divisions monthly income for the current month While the monthly income is negative Display an error message Get the current divisions monthly income for the current month Add the monthly income to the annual income for the division Display the annual income for the current division Add the current divisions annual income to the companys annual income Display the annual income for the company
49
When I am working on a program, I include debug statements to help me ensure that my program is working as I planned. In a program like this one, I would display the value of the counter(s), the value(s) entered by the user, and the value of the accumulator(s) in each iteration of the loop. I take the debug statements out when I have completed the testing of the program.
50
NESTED LOOPS
The inner loop of a nested loop goes through all of its iterations for each iteration of the surrounding loop.
Note: The statements in the inner for loop of IncomeByDivision.java, that are outside the while loop execute 3 12 = 36 times.
51
When a break statement is encountered inside a loop, execution immediately goes to the first statement following the loop. When a break statement is encountered multiple levels deep inside a nested loop, only the loop immediately surrounding the break is exited.
52
The continue statement causes a loop to stop its current iteration and begin the next iteration. In a while or do-while loop this means that the execution automatically goes to the evaluation of the continuation expression. If the expression is true, the next iteration begins. In a for loop, this means the execution automatically goes to the update portion of the loop header. The update is executed and then the continuation expression is evaluated. If the expression is true, the next iteration begins.
53
Avoid using the break and continue statements in loops. They make it more difficult to follow the logic of the program.
54
A repetitive algorithm can be implemented using any of the three loops: while, do-while, or for. The for loop is well-suited to situations where the exact number of iterations is known. The initialization, continuation, and update expressions can be specified inside the parentheses at the top of the loop. The for loop was designed to simplify the writing of countcontrolled loops. The do-while loop is ideal for situations where you always want the loop to iterate at least once. The do-while loop is a good choice for repeatedly displaying a menu. The while loop is ideal for situations where you do not want the loop to iterate if a condition is false from the beginning. Sentinelcontrolled loops and loops to read an unknown number of items from a file can be more elegantly encoded using a while loop.
55
56
57
58
59
60
61
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
When we want to write data to a file we will create an instance of the PrintWriter class. The second statement creates an object of the PrintWriter class and assigns the address of the object created to the reference variable named outputFile.
File theFile = new File(students.txt"); PrintWriter outputFile = new PrintWriter(theFile);
62
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
We are passing a reference to a File object to the constructor of the PrintWriter class. The constructor method creates an empty file and establishes a connection between the file and the PrintWriter object. In our example, a file named students.txt will be created in the current working directory, opened to receive data, and linked with the outputFile object.
File theFile = new File(students.txt"); PrintWriter outputFile = new PrintWriter(theFile);
We are passing the reference variable named theFile to the PrintWriter constructor.
63
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
If the file you open with a PrintWriter object already exists, the file will be erased and an empty file will be created.
64
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
You can test if a file exists by using the exists( ) method of a File object. The exists( ) method returns the value true if the file exists. The exists( ) method returns the value false if the file does not exist.
65
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
If you dont want to erase the file if it already exists, test whether the file exists before creating the PrintWriter object.
File theFile = new File(students.txt"); PrintWriter outputFile; if(theFile.exists( )) // If the file already exists { System.out.println("The file students.txt already exists."); } else // The file does not already exist { // Create the file, open it, and link it with outputFile outputFile = new PrintWriter(theFile); }
66
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Once you have opened the file by creating an object of the PrintWriter class, you can write data to the file using the print( ) and/or println( ) methods of the object. You already know how to use the print( ) and println( ) methods of the System.out object to display data in a console window. The print( ) and println( ) methods of a PrintWriter object work in much the same way.
67
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
For example, the statement below writes the name Niklas Hagman followed by a newline character to the file connected to the PrintWriter object referenced by outputFile.
outputFile.println(Niklas Hagman);
68
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Data is written to a file as a continuous stream of characters. For example:
outputFile.println("Niklas Hagman"); outputFile.println("Stu Barnes"); outputFile.println("Sergei Zubov");
The data above is written to the file linked with outputFile as:
Niklas Hagman<newline>Stu Barnes<newline>Sergei Zubov<newline>
We are representing the newline character with <newline>. The newline character separates or delimits the individual data items.
69
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
outputFile.println("Niklas Hagman"); outputFile.println("Stu Barnes"); outputFile.println("Sergei Zubov");
When you open the file in Notepad you will see the following. The text editor interprets the newline character as a command to go to the next line.
70
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
The print( ) method does not write the newline character after the data item.
71
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
For example, when the following statements are executed the contents of the file when viewed in Notepad are:
String name = "Jenny"; String phone = "867-5309"; outputFile.print(name + " "); outputFile.print(phone);
72
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Adding a throws Clause to the Method Header In Java, many run-time errors are called exceptions. We say that a Java program throws an exception when certain errors occur. For this course we will think of an exception as a signal that the program cannot continue unless the problem is dealt with. For example, if you try to create a PrintWriter object to open a file, but the file cannot be created because there is not enough available disk space, the PrintWriter object throws an exception of the IOException type.
73
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Adding a throws Clause to the Method Header When an exception is thrown, the executing method can either deal with the exception or throw it again. If the main( ) method throws an exception, the program terminates and an error message is displayed. In this class, we will simply allow our methods to rethrow any exceptions.
74
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Adding a throws Clause to the Method Header To allow a method to rethrow an exception we write a throws clause in the method header. An example of this is shown in the main( ) method header below:
public static void main(String[ ] args) throws IOException
Any method that uses a PrintWriter object, or any method that calls a method that uses a PrintWriter object and does not deal with the problem signaled by the exception must have this throws clause in its header. Otherwise, the program will not compile. 75
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Closing a File After you are done using a file you should close it using the close( ) member function of the PrintWriter object.
outputFile.close( );
76
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
Closing a File
Most operating systems temporarily write output destined for a file to a file buffer in the computers main memory. When the buffer is filled, the contents of the buffer are written to the file. This improves system performance since interaction with secondary storage is slower than main memory. The close( ) method writes any data that is still in the buffer to the file. Until you close the file, your data may not be in the file on a nonvolatile secondary storage device. Once the file is closed, the connection between the file and the PrintWriter object is removed. In order to access the file using the PrintWriter object, the file must be reopened.
77
INTRODUCTION TO FILE INPUT AND OUTPUT Using the PrintWriter class to Write Data to a File
When writing data to a text file: 1. Include the statement import java.io.*; before the class definitions of your source file. 2. Put the throws IOException clause in the method header of any method that uses a PrintWriter object or calls a method that uses a PrintWriter object. 3. Create an object of the File class in memory. Pass the name of the file as the argument to the constructor. 4. Test if the file already exists using the File objects exists( ) member method if you dont want to erase an existing file. 5. Create a PrintWriter object in memory. Pass the reference to the File object created above as the argument to the constructor. The file represented by the File object will be created in memory, linked with the PrintWriter object, and opened for writing. 6. Use the PrintWriter objects member methods println( ) and/or print( ) to write data to the file. 79 7. Use the PrintWriter objects close( ) member method to close the file.
80
81
82
Then create an object of the Scanner class that is linked to the File object by writing a statement like the following:
Scanner inputFile = new Scanner(studentFile);
Notice, that in the statement above, we are passing a reference to a File object to the constructor of the Scanner class. This statement opens an existing file for input and links it with the object referenced by inputFile. In our example, the file named students.txt is opened in the current working directory. 83
84
85
Remember, the nextLine( ) method reads through the newline character, but does not put the newline character in the string. Reading characters from a file does not remove them from the file, they are still in the file.
87
90
91
93