1 Fall 2007ACS-1903 for Loop Writing to a file String conversions Random class.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 4: Loops and Files
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
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.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Guide To UNIX Using Linux Third Edition
Chapter 3b Standard Input and Output Sample Development.
11 Chapter 4 LOOPS AND FILES CONT’D. 22 SENTINEL-CONTROLLED LOOPS Suppose we did not know the number of grades that were to be entered. Maybe, a single.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 4.
CS0007: Introduction to Computer Programming File IO and Recursion.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Chapter 4: Loops and Files
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
Input and Output Using Text Files and Exception Handling.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Loops and Files Starting Out with Java From Control Structures.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
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.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
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.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
1 Fall 2009ACS-1903 Writing Data To a File When writing to a file we need objects from the following classes are used to write data to files: FileWriter.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 4 Loops and Files. 2 Contents 1. The Increment and Decrement Operators 2. The while Loop 3. Using the while Loop for Input Validation 4. The do-while.
Information and Computer Sciences University of Hawaii, Manoa
Loop Structures.
Lecture 4- Loops and Files
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
I/O Basics.
Chapter 4: Loops and Files
Chapter 4: Loops and Files by Tony Gaddis and Godfrey Muganda
Topics Introduction to File Input and Output
Outline Altering flow of control Boolean expressions
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 4: Loops and Files
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Ch.4 – 5 Topics The auto Increment and Decrement Operators
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.
Topics Introduction to File Input and Output
Presentation transcript:

1 Fall 2007ACS-1903 for Loop Writing to a file String conversions Random class

2 Fall 2007ACS-1903 for Loop a specialized form of the while loop … a pre-test loop. The for loop allows the programmer to initialize a control variable, test a condition, and modify the control variable all in one line of code. The for loop takes the form: for(initialization; test; update) { loop statements; } Example: Squares.javaSquares.java

3 Fall 2007ACS-1903 The for Loop Flowchart statement(s) true boolean expression? false update initialization

4 Fall 2007ACS-1903 for Loop The initialization section … initialize its control variable. The test section of the for statement is similar to the test in a while loop. The update section of the for loop is the last thing to execute in the loop. Example: UserSquares.javaUserSquares.java

5 Fall 2007ACS-1903 The for Loop Initialization Optional - however, usually provided. Typically, for loops initialize a counting variable Can initialize multiple variables. Variables declared in this section have scope only for the for loop.

6 Fall 2007ACS-1903 The Update Expression usually used to increment or decrement the counting variable(s) last section to execute in the loop. may update multiple variables. Each variable updated is executed as if it were on a line by itself.

7 Fall 2007ACS-1903 Modifying The Control Variable bad programming style to update the control variable of a for loop within the body of the loop - leads to hard to maintain code and difficult debugging. update section should be used to update the control variable.

8 Fall 2007ACS-1903 Multiple Initializations and Updates The for loop may initialize and update multiple variables. for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2){ loop statements; } only the semicolons are mandatory. for(;;){ loop statements; }//infinite loop. If left out, the test section defaults to true.

9 Fall 2007ACS-1903 Nested Loops Like if statements, loops can be nested. If a loop is nested, the inner loop will execute all of its iterations for each time the outer loop executes once. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) loop statements; The loop statements in this example execute 100 times. Example: Clock.javaClock.java

10 Fall 2007ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops bypasses the normal mechanisms and makes the code hard to read and maintain. considered bad form to use the break statement in this manner.

11 Fall 2007ACS-1903 The continue Statement a continue statement will cause the currently executing iteration of a loop to terminate and the next iteration will begin. a continue statement will cause the evaluation of the condition in while and for loops. as with the break statement, the continue statement should be avoided because it makes the code hard to read and debug.

12 Fall 2007ACS-1903 Deciding Which Loops to Use The while loop: Pretest loop Use it where you do not want the statements to execute if the condition is false in the beginning. The do-while loop: Post-test loop Use it where you want the statements to execute at least one time. The for loop: Pretest loop Use it where there is some type of counting variable that can be evaluated.

13 Fall 2007ACS-1903 Files Input … reading Output … writing Errors can occur Attempting to read a file that does not exist Writing to a file that is protected These types of errors need to be provided for

14 Fall 2007ACS-1903 Exceptions When something unexpected happens in a Java program, an exception is thrown. The method currently executing when the exception is thrown must either handle the exception or pass it up the line. Handling the exception is discussed later. To pass it up the line, the method needs a throws clause in the method header.

15 Fall 2007ACS-1903 Exceptions To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. The class Exception can be used to catch all exceptions. public static void main(String[] args) throws IOException{…} File I/O is a checked exception (meaning the exception must be handled or passed up). A program with file I/O will generate a compile-time error if the exception is not handled or passed up. Example: FileWriteDemo.javaFileWriteDemo.java

16 Fall 2007ACS-1903 Writing Data To a File When writing to a file we need objects from the following classes are used to write data to files: FileWriter – This class allows basic file writing functionality. PrintWriter – This class allows the programmer to write files using the same style that is used to write to the screen (i.e. print and println).

17 Fall 2007ACS-1903 The FileWriter Class The FileWriter clas provides other classes with the basic file writing functionality. System.out.println(“Enter the filename.”); filename = Keyboard.readString(); FileWriter fwriter = new FileWriter(filename); This will create an object that can access the file filename. Warning: if the file above already exists, it will be erased and replaced with the new file.

18 Fall 2007ACS-1903 The PrintWriter Class The PrintWriter class adds to the functionality of the FileWriter class. The PrintWriter cannot directly access the file but must work through the FileWriter class. The PrintWriter needs a FileWriter object in order to work: FileWriter fwriter = new FileWriter("StudentData.txt"); PrintWriter outputFile = new PrintWriter(fwriter);

19 Fall 2007ACS-1903 The PrintWriter Class Once linked to the fwriter object, the outputFile object can talk to the file. outputFile.println(“Jim”); outputFile.close(); Just as with the System.out object, the println method of the PrintWriter class will place a newline character after the written data. The print method can be used to avoid writing the newline character.

20 Fall 2007ACS-1903 Appending Text to a File To avoid erasing a file that already exists: Create a FileWriter object using an optional boolean argument that tells the object to append data to the file. FileWriter fwriter = new FileWriter(“filename”, true); Data written to a file created in such a manner will be appended to the end of the current file.

21 Fall 2007ACS-1903 Specifying a File Location Windows’ Crazy Backslash Windows evolved from DOS. Since DOS was simply a hacked version of CP/M, it maintained the backslash (\) as a directory separator. Remember, if the backslash is used in a String literal, it is the escape character so there must be two of them. FileWriter fwriter = new FileWriter("A:\\PriceList.txt"); PrintWriter outputFile = new PrintWriter(fwriter);

22 Fall 2007ACS-1903 Specifying a File Location This is only necessary if the backslash is in a String literal. If the backslash is in a String object then it will be handled properly. Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories. FileWriter fwriter = new FileWriter("/home/rharrison/names.txt"); PrintWriter outputFile = new PrintWriter(fwriter);

23 Fall 2007ACS-1903 Reading Data From a File Java provides several classes to read data from a file. FileReader Open an existing file for reading and establish a connection with it. BufferedReader Uses a buffer to allow the reading of full lines of text at a time rather than one byte at a time.

24 Fall 2007ACS-1903 Detecting The End of a File The readLine() method of the BufferedReader class will return null if the end of the file has been reached. FileReader freader = new FileReader(filename); BufferedReader inputFile = new BufferedReader(freader); // Read the first item. String str = inputFile.readLine(); // If an item was read, display it // and read the remaining items. while (str != null) { System.out.println(str); str = inputFile.readLine(); } inputFile.close();// close the file when done. We say end-of-file occurs when we read a line, but there are no more lines left to read. End-of-file is detected by checking for a null line.

25 Fall 2007ACS-1903 String Value Conversion The readLine() method of the BufferedReader class only reads in text as a String object. Strings that represent numbers can be converted and stored into primitive variables. Java provides wrapper classes that make conversion easy.

26 Fall 2007ACS-1903 String Value Conversion MethodDescription Integer.parseInt(str) This method accepts a string that contains a number and returns the number as an int. Short.parseShort(str) This method accepts a string that contains a number and returns the number as a short. Byte.parseByte(str) This method accepts a string that contains a number and returns the number as a byte. Long.parseLong(str) This method accepts a string that contains a number and returns the number as a long. Float.parseFloat(str) This method accepts a string that contains a number and returns the number as a float. Double.parseDouble(str) This method accepts a string that contains a number and returns the number as a double. Example: FileSum.javaFileSum.java

27 Fall 2007ACS-1903 The Random Class Some applications, such as games and simulations, require the use of randomly generated numbers. The Java API has a class, Random, for this purpose. To use the Random class, use the import statement and create an instance of the class. import java.util.Random; Random randomNumbers = new Random();

28 Fall 2007ACS-1903 Some Methods of the Random Class MethodDescription nextDouble() Returns the next random number as a double. The number will be within the range of 0.0 and 1.0. nextFloat() Returns the next random number as a float. The number will be within the range of 0.0 and 1.0. nextInt() Returns the next random number as an int. The number will be within the range of an int, which is –2,147,483,648 to +2,147,483,648. nextInt(int n) This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n. Example: MathTutor.javaMathTutor.java

29 Fall 2007ACS-1903 Example Suppose we want to program a game that involves two dice. Die will be a class from which we can instantiate two objects (one for each die). We can toss the pair of dice 1,000,000 times and see what the average throw is. ASIDE: a UML class diagram showing the classes the program has, each of their attributes and methods, and the relationships between classes. Random 21 Die DiceGame numberSides generator toss() die1 die2 main() nextInt() A dicegame is played with two dice A die uses a random number generator DiceGame.javaDie.java Java code: Using BlueJ

30 Fall 2007ACS-1903 ASIDE: a UML sequence diagram showing how the objects interact DiceGame main() die1:Die new() die2:Die new() : Random new() toss() Loop [1,000,000 times] System.out printLn() toss() Die is a class from which we instantiate two objects. We toss the pair of dice 1,000,000 times. new() :Random printLn() nextInt()