1 Chapter 5 File Objects and Looping Statements. 2 Chapter 9 Topics l Using Data Files for I/O l While Statement Syntax l Count-Controlled Loops l Event-Controlled.

Slides:



Advertisements
Similar presentations
Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
1 Lecture 15 Chapter 6 Looping Dale/Weems/Headington.
Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
1 Lecture 16 Chapter 6 Looping Dale/Weems/Headington.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Chapter 6 Looping Dale/Weems. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
1 Fall 2007ACS-1903 for Loop Writing to a file String conversions Random class.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
1 Chapter 5 File Objects and Looping Statements (Some slides have been modified from their original format)
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Chapter 6 Looping.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 6 Looping. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition to.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 5: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Lecture 3 Looping and FIiling. 5-2 Topics – The Increment and Decrement Operators – The while Loop – Using the while Loop for Input Validation – The do.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
1 Chapter 9 File I/O and Looping. 2 Chapter 9 Topics l Using Data Files for I/O l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 6 Loops and Files
Chapter 4 Repetition Statements (loops)
Chapter 6 Looping.
Chapter 5: Control Structures II
Loop Structures.
Repetition-Counter control Loop
Loops A loop is a repetition control structure.
Repetition Statements
Presentation transcript:

1 Chapter 5 File Objects and Looping Statements

2 Chapter 9 Topics l Using Data Files for I/O l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition l Using a While Statement for Summing and Counting l Nested While Loops l Loop Testing and Debugging

3 To Use File I/O, you must Import package java.io.* l Choose valid identifiers and types for your file variables and declare them l Instantiate a file object for each file variable Use your file identifiers in your I/O statements (using available methods such as readLine, print, println ) l Close the files when through

4 What does instantiating a file do? l Associates the Java identifier for your file with the physical (disk) name for the file l Places a file pointer at the very beginning of the file, pointing to the first character in it l If the output file does not exist on disk, an empty file with that name is created l If the output file already exists, it is erased

5 Using files for I/O your variable ( of type BufferedReader) your variable (of type PrintWriter) disk file “myInfile.dat” disk file “myOutfile.dat” executing program input dataoutput data import.java.io.*;

6 readLine() method readLine() method of BufferedReader class uses no parameters and returns an object of class String. l It reads a line of input from the file, including the end-of-line mark, discards the EOL mark, and returns the rest of the line String line; line = inFile.readLine();

7 How do you read a number? Read a string and convert it to a number int numberOfDependents; line = inFile.readLine(); numberOfDependents = Integer.parseInt(line); double taxRate; line = inFile.readLine(); taxRate = Double.parseDouble(line);

8 print() and println() methods print() writes its parameters on the file to which the method is applied println() is just like print, but it appends an end- of-line before returning. Sound familiar? print and println in class PrintWriter behave exactly the same as those methods of the same name we have used with System.out

9 l An exception is an unusual situation detected while a program is running; it halts the normal execution of the method l Java recognizes two types of exceptions, checked and unchecked l Unchecked exceptions can be ignored, but checked exceptions must be explicitly recognized by the program I/O Methods and Exceptions

10 Forwarding an exception l An exception can be forwarded by adding a throws clause to a method heading. The clause specifies the name of the exception that is being forwarded public static void main(String[ ] args) throws IOException l The exception is passed to the method’s caller, until an exception handler is found, or passing terminates with the JVM

11 BufferedReader and FileWriter classes throw an exception called IOException. PrintWriter does not throw any exceptions, but the PrintWriter constructor must be passed a FileWriter object that can throw an IOException l More about exceptions in Chapter 9 IOException

12 l A loop is a repetition control structure l It causes a single statement or block to be executed repeatedly while an expression is true What is a loop?

13 Two types of loops count-controlled loops repeat a specified number of times event-controlled loops something happens inside the loop body that causes the repetition to stop

14 While Statement while ( Expression ) {.. // loop body. } NOTE: Loop body can be a single statement, a null statement, or a block

15 When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the loop body WHILE LOOP false true body statement Expression

16 An initialization of the loop control variable l An expression to test for continuing the loop l An update of the loop control variable to be executed within each iteration of the body Count-controlled loops contain

17 int loopCount; // Declare loop variable loopCount = 1; // Initialize loop variable while (loopCount <= 10) // Test expression {. // Repeated actions. loopCount = loopCount++; // Update loop variable } Count-controlled Pattern

18 int count; // Declare loop variable count = 1;// Initialize loop variable while (count <= 4)// Test expression { // Repeated action System.out.println(“count is “ + count); count ++; // Update loop variable } System.out.println(“Done”); Count-controlled Example

19 Count-controlled loop int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println(“Done”); OUTPUT count

20 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count 1

21 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 1 OUTPUT

22 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 1 OUTPUT count is 1

23 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 2 OUTPUT count is 1

24 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 2 OUTPUT count is 1

25 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count 2

26 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 3 OUTPUT count is 1 count is 2

27 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 3 OUTPUT count is 1 count is 2

28 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count 3

29 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count 4

30 int count; count = 1; while ( count <= 4 ) { TRUE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 4 OUTPUT count is 1 count is 2 count is 3

31 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count is 4 count 4

32 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); OUTPUT count is 1 count is 2 count is 3 count is 4 count 5

33 int count; count = 1; while ( count <= 4 ) { FALSE System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 5 OUTPUT count is 1 count is 2 count is 3 count is 4

34 int count; count = 1; while ( count <= 4 ) { System.out.println ( “count is “ + count ); count++; } System.out.println( “Done” ); count 5 OUTPUT count is 1 count is 2 count is 3 count is 4 Done

35 dataFile contains 100 blood pressures, one to a line Use a while loop to read the 100 blood pressures and find their total Count-Controlled Loop Example

36 // Count-controlled loop int thisBP; int total; int count; count = 1;// Initialize total = 0; while (count <= 100)// Test expression { thisBP = Integer.parseInt(dataFile.readLine()); total = total + thisBP; count++; // Update } System.out.println(“The total = “ + total);

37 Event-controlled loops l Sentinel controlled Keep processing data until a special value which is not a possible data value is entered to indicate that processing should stop l End-of-file controlled Keep processing data as long as there is more data in the file l Flag controlled Keep processing data until the value of a flag changes in the loop body

38 Examples of kinds of loops Count controlled loop Read exactly 100 blood pressures from a file. End-of-file controlled loop Read all the blood pressures from a file no matter how many are there. Flag controlled loop Read blood pressures until a dangerously high BP (200 or more) is read.

39 A sentinel-controlled loop l Requires a “priming read” l “Priming read” means you read one data value (or set of data values) before entering the while loop l Process data value(s) and then read next value(s) at end of loop

40 // Sentinel is negative blood pressure. int thisBP; int total; int count; count = 1;// Initialize total = 0; // Priming read thisBP = Integer.parseInt(dataFile.readLine()); while (thisBP > 0)// Test expression { total = total + thisBP; count++; // Update thisBP = Integer.parseInt(dataFile.readLine()); } System.out.println(“The total = “ + total);

41 An end-of-file controlled loop depends on fact that readLine returns null if there is no more data

42 // Read and sum until end of line int thisBP; int total; int count; count = 1;// Initialize total = 0; String line; line = dataFile.readLine(); while (line != null)// Test expression { thisBP = Integer.parseInt(line); total = total + thisBP; count++; // Update line = dataFile.readLine(); } System.out.println(“The total = “ + total);

43 Flag-controlled loops l Use meaningful name for the flag l Initialize flag (to true or false) l Test the flag in the loop test expression l Change the value of the flag in loop body when the appropriate condition occurs

44 A flag-controlled loop l Count and sum the first 10 odd numbers in a data file Initialize flag notDone to true Use while(notDone) for loop test Change flag to false when 10 odd numbers have been read or if EOF is reached first

45 count = 0; sum = 0; notDone = true; while ( notDone ) { line = dataFile.readLine( ); // Get a line if (line != null) // Got a line? { number = Integer.parseInt(line); if (number % 2 == 1) // Is number odd? { count++; sum = sum + number; notDone = ( count < 10 ); } else // Reached EOF unexpectedly { errorFile.println(“EOF reached before ten odd values.”) notDone = false; // Change flag value }

46 Loops often used to l Count all data values l Count special data values l Sum data values

47 // Flag and EOF controlled loop countGoodReadings = 0; // Initialize isSafe = true; while (isSafe && (line = dataFile.readLine() != null)) { thisBP = Integer.valueOf(line).intValue(); if (thisBP >= 200) isSafe = false; // Change flag else countGoodReadings++; // Update } System.out.println(“There were ” + countGoodReadings + “ safe blood pressure readings.”);

48 initialize outer loop while ( outer loop condition ) {... initialize inner loop while ( inner loop condition ) { inner loop processing and update }... } Pattern of a nested loop

49 Nested loop design l Begin with outer loop l When you get to where the inner loop appears, make it a separate module and come back to its design later

50 Algorithm uses Nested Loops l Get a data line from the data file l While more data nobtain starCount from the data line nuse a count-controlled loop to print starCount asterisks to the output file nprint a newline character to the output file nread next data line from the data file l Print “End” to the output file

51 // Using nested loops line = dataFile.readLine(); // Get data line while (line != null) // While more data { starCount = Integer.parseInt(line); loopCount = 1; // Loop to print asterisks while (loopCount <= starCount) { outFile.print(‘*’); loopCount ++; } outFile.println(); line = dataFile.readLine(); // Get next data line } outFile.println(“End”);

52 Information about 20 books in file bookfile.dat P 3.98 H 7.41 P Price of bookHardback or Paperback? Write a program to find total value of all books

53 String line; // Declarations String kind; double price; double total = 0.0; int count = 1; while (count <= 20) { line = dataFile.readLine() kind = line.substring(0, 1); price = Double.parseDouble( line.substring(1, line.length())); total = total + price; count ++; }

54 Trace of Program Variables count kind price total “P” “H” “P” etc so loop terminates

55 Accessing characters in a line readLine reads a line of text from a file l Lines are converted to numbers using methods in numeric classes How do you access the characters in a line? line.charAt(index) returns the character at the index position in the line line.charAt(0) is the first character; line.charAt(line.length()-1 ) is the last character

56 // Counts number of commas on each line of data lineCount = 0; inLine = inFile.readLine(); // Priming read while (inLine != null) // Outer loop test for EOF { lineCount++; commaCount= 0; index = 0; // Initialize loop count while (index < inLine.length()) { if (inLine.charAt(index) == ',') commaCount++; index++; } System.out.println("Found " + commaCount + " commas on line " + lineCount); inLine = inFile.readLine(); //Update outer exit condition } System.out.println("There are " + lineCount + " lines in the file.");

57 Loop Definitions l Iteration counter A counter variable that is incremented in each iteration of a loop l Event counter A variable that is incremented each time a particular event occurs

58 Object State l The object’s state is the current set of values that it contains l An object is instantiated with an initial state. If any of its methods can subsequently change its state, the object is said to be mutable l Methods that change an object’s state are called transformers

59 C lass TrafficLight TrafficLight knowCurrentColor knowTimeRemaining. changeColor Private data: currentColor timeRemaining decrementTimeRemaining

60 Loop Testing and Debugging Test data should test all sections of the program l Beware of infinite loops -- the program doesn’t stop l Check loop termination condition, and watch for an OBOB (off-by-1 bug) l Use algorithm walk-through to verify that appropriate conditions occur in the right places l Trace execution of loop by hand with code walk-through l Use a debugger (if available) to run program in “slow motion” or use debug output statements