Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.

Slides:



Advertisements
Similar presentations
More Java Syntax. Scanner class Revisited The Scanner class is a class in java.util, which allows the user to read values of various types. There are.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Numeric literals and named constants. Numeric literals Numeric literal: Example: A numeric literal is a constant value that appears in a Java program.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
18 File handling1June File handling CE : Fundamental Programming Techniques.
Nested conditional statements. Previously discussed Conditional statements discussed so far: Syntax of the if-statement: if-statement if-else-statement.
The switch statement: an N-way selection statement.
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Programming a computer. What does programming a computer mean ? Programming a computer: Since a computer can only execute machine instructions (encoded.
The break and continue statements. Introduction There are 2 special statements that can affect the execution of loop statements (such as a while-statement)
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
The for-statement. Different loop-statements in Java Java provides 3 types of loop-statements: 1. The for-statement 2. The while-statement 3. The do-while-statement.
Shorthand operators.
The character data type char
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
CSI 1390: Introduction to Computers TA: Tapu Kumar Ghose Office: STE 5014
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
The Rectangle Method. Introduction Definite integral (High School material): A definite integral a ∫ b f(x) dx is the integral of a function f(x) with.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
The dangling-else ambiguity. Previously discussed The Java compiler (translator) consider white space characters (i.e., SPACE, TAB and New line) as insignificant.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Floating point numerical information. Previously discussed Recall that: A byte is a memory cell consisting of 8 switches and can store a binary number.
The scope of local variables. Murphy's Law The famous Murphy's Law says: Anything that can possibly go wrong, does. (Wikipedia page on Murphy's Law:
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Working with arrays (we will use an array of double as example)
Assignment statements using the same variable in LHS and RHS.
CSci 111 – computer Science I Fall 2014 Cynthia Zickos WRITING A SIMPLE PROGRAM IN JAVA.
Mixing integer and floating point numbers in an arithmetic operation.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Integer numerical data types. The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number.
The while-statement. Syntax and meaning of the while-statement The LOOP-CONTINUATION-CONDITION is a Boolean expression (exactly the same as in the condition.
The assignment expressions. The assignment operator in an assignment statement We have seen the assignment statement: Effect: var = expr; Stores the value.
The while-statement. The loop statements in Java What is a loop-statement: A loop-statement is a statement that repeatedly executes statements contained.
Arithmetic expressions containing Mathematical functions.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Working with floating point expressions. Arithmetic expressions Using the arithmetic operators: and brackets (... ), we can construct arithmetic expression.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Simple algorithms on an array - compute sum and min.
Files Review For output to a file: –FileOutputStream variable initialized to filename (String) and append/not append (boolean) –PrintWriter variable initialized.
The ++ and -- expressions. The ++ and -- operators You guessed it: The ++ and -- are operators that return a value.
Computer Science A 1. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated editor,
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
CSC111 Quick Revision.
Introduction to programming in java
Input/Output.
CSC1401 Input and Output (and we’ll do a bit more on class creation)
Exceptions and User Input Validation
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
Computer Programming Methodology Input and While Loop
TK1114 Computer Programming
Something about Java Introduction to Problem Solving and Programming 1.
INPUT STATEMENTS GC 201.
The Boolean (logical) data type boolean
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
Introduction to Java Brief history of Java Sample Java Program
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
The for-statement.
Presentation transcript:

Using the while-statement to process data files

General procedure to access a data file General procedure in computer programming to read data from a data file 1. Open the data file You provide the name of the data file to an "open a file" library function that will open the data file (Different programming languages will provide a different "open a file" library function) This "open a file" library function will return some information (let's call it X) back to you that you can use to access the opened file That information is used in the computer to identified the opened file

General procedure to access a data file 2. With the information X, you can then use a "read something from a file" method to read data from the opened file 3. There are other helpful methods on an opened file. Some method let you check if you have reached the end of the file

Previously discussed: reading from the keyboard Summary: reading a floating point number from the keyboard

Previously discussed: reading from the keyboard (cont.) The methods in the Scanner class can also be used to read input data from a file

Opening a data file How to open a file in Java: The variable myFile contains information about the opened file The variable myFile will be used in read operations File myFile; // Define a "File" type variable to receive // the opened file myFile = new File("Path-name-of-the-file"); // Open the file

Scanning an opened file Reading data from an opened file is a very complex task Fortunately: An opened file behaves exactly like a keyboard (which is represented by the variable System.in in Java)

Scanning an opened file (cont.) We can use the method in the Scanner class to help us read and convert the data into the desired encoding

Scanning an opened file (cont.) Previously discussed: To construct a Scanner object using the keyboard System.in: Scanner in; // Define a Scanner typed variable in = new Scanner(System.in); // Construct a Scanner that read // data from keyboard System.in

Scanning an opened file (cont.) Read from a data file: Construct a Scanner object using an opened file: /* Open a data file */ File myFile; // Define a "File" type variable to receive // the opened file myFile = new File("Path-name-of-the-file"); // Open the file /* Construct a Scanner from the opened file "myFile" */ Scanner in; // Define a Scanner typed variable in = new Scanner(myFile); // Construct a Scanner that read // data from opened file"myFile"

Scanning an opened file (cont.) From this point onwards, you can use in.nextDouble() to read a floating point number from the data file in.nextInt() to read an integer number from the data file in.next() to read a string (word) from the data file

Checking for available input data There are very useful methods available in the Scanner class to test if the input file is empty (exhausted) or not.

Checking for available input data (cont.) Check function for input availability on Scanner typed variable in: in.hasNextDouble() returns true if the Scanner object in contains at least one double typed value in the input. returns false otherwise (no more double typed value in the input.)

Checking for available input data (cont.) in.hasNextInt() returns true if the Scanner object in contains at least one int typed value in the input. returns false otherwise (no more int typed value in the input.)

Checking for available input data (cont.) in.hasNext() returns true if the Scanner object in contains at least one String typed value in the input. returns false otherwise (no more String typed value in the input.)

Checking for available input data (cont.) OK, we have covered everything we need to process data files in Java !

Programming example 1: print the content of a data file Let's start simple: Write a Java program that read the data from the file inp1 and... print each word read to the terminal.

Programming example 1: print the content of a data file (cont.) Rough algorithm: Open the file "inp1" Construct a Scanner object using the opened file as long as ( there is data in the Scanner object ) { read a word from the Scanner object; print the word; }

Programming example 1: print the content of a data file (cont.) Algorithm in Structure Diagram form: (I have used the initialization form to define the variables myFile and in for brevity.)

Programming example 1: print the content of a data file (cont.) Java program: import java.io.*; import java.util.Scanner; public class File01 { public static void main(String[] args) throws IOException { File myFile = new File("inp1"); // Open file "inp1" Scanner in = new Scanner(myFile); // Make Scanner obj with opened file String x; // Variable to receive a string while ( in.hasNext() ) { x = in.next(); // Read a string (word) System.out.println(x); // Print string read } System.out.println("Done"); }

Programming example 1: print the content of a data file (cont.) Additional programming code needed: The File class is contained inside the java.io package We need to use the import statement: import java.io.File;

Programming example 1: print the content of a data file (cont.) However, the methods in the File class need other methods in the java.io package That's why we import all class in the java.io package with the import statement import java.io.*;

Programming example 1: print the content of a data file (cont.) File read errors in the java.io package are reported by exceptions A method that uses methods in the java.io package must contain the declaration Exceptions is a very advanced programming concept that is not discussed in this course.... throws IOExceptions

Programming example 1: print the content of a data file (cont.) Example Program: (Demo above code) –Prog file: File01.java –Input data file inp1: np1 How to run the program: Right click on both links and save in a scratch directory To compile: javac File01.java To run: java File01

Programming example 1: print the content of a data file (cont.) Example run: Input file inp1: Hello Class This is your first input data file !

Programming example 1: print the content of a data file (cont.) Output of the program: Hello Class This is your first input data file ! Done

Programming example 2: sum the (floating point) data in a data file Programming problem: Given a data file inp2 that contains a (unspecified number) floating point numbers Write a Java program that read the data from the file inp2 and... print the sum of the numbers to the terminal.

Programming example 2: sum the (floating point) data in a data file (cont.) Rough algorithm: Open the file "inp2" Construct a Scanner object using the opened file sum = 0; // Initial value ("clear the slate") as long as ( there is a double datum in the Scanner object ) { Read a floating point number from the Scanner object; Add the number to the sum; } Print sum;

Programming example 2: sum the (floating point) data in a data file (cont.) Algorithm in Structure Diagram form:

Programming example 2: sum the (floating point) data in a data file (cont.) Java program: import java.io.*; import java.util.Scanner; public class File01 { public static void main(String[] args) throws IOException { File myFile = new File("inp2"); // Open file "inp2" Scanner in = new Scanner(myFile); // Make Scanner obj with opened file double x; // Variable to receive a floating point number double sum; // Running sum

Programming example 2: sum the (floating point) data in a data file (cont.) sum = 0.0; // Initialize ("clear the slate") while ( in.hasNextDouble() ) { x = in.nextDouble(); // Read a floating point number sum = sum + x; // Add to the running sum } System.out.println("Sum = " + sum); }

Programming example 1: print the content of a data file (cont.) Example Program: (Demo above code) –Prog file: File02.java –Input data file inp1: np2 How to run the program: Right click on both links and save in a scratch directory To compile: javac File02.java To run: java File02

Programming example 1: print the content of a data file (cont.) Example run: Input file inp2: Output of the program: Sum = 17.6

Programming example 3: compute the average of (floating point) data in a data file Programming problem: Given a data file inp3 that contains a (unspecified number) floating point numbers Write a Java program that read the data from the file inp3 and... print the average of the numbers to the terminal.

Programming example 3: compute the average of (floating point) data in a data file (cont.) Computing the average: The average of a series of numbers can be computed by maintaining the following information: the running sum the number of items that was added into the running sum

Programming example 3: compute the average of (floating point) data in a data file (cont.) Example: Input: 2.1, 3.2, 2.2, 1.3 Running sum = 10.8 Number of items = 4 Average = 10.8/4 = 2.7

Programming example 3: compute the average of (floating point) data in a data file (cont.) Rough algorithm: Open the file "inp3" Construct a Scanner object using the opened file sum = 0; // Initial value ("clear the slate") N = 0 // # items added into sum as long as ( there is a double datum in the Scanner object ) { Read a floating point number from the Scanner object; Add the number to the sum; N++; } Print sum/N; // print average

Programming example 3: compute the average of (floating point) data in a data file (cont.) Algorithm in Structure Diagram form:

Programming example 3: compute the average of (floating point) data in a data file (cont.) Java program: import java.io.*; import java.util.Scanner; public class File01 { public static void main(String[] args) throws IOException { File myFile = new File("inp2"); // Open file "inp2" Scanner in = new Scanner(myFile); // Make Scanner obj with opened file double x; // Variable to receive a floating point number double sum; // Running sum int N; // # items added **** New code

Programming example 3: compute the average of (floating point) data in a data file (cont.) sum = 0.0; // Initialize ("clear the slate") N = 0; // No items added **** New code while ( in.hasNextDouble() ) { x = in.nextDouble(); // Read a floating point number sum = sum + x; // Add to the running sum N++; // One more item added **** New code } System.out.println("Average = " + sum/N); }

Programming example 3: compute the average of (floating point) data in a data file (cont.) Example Program: (Demo above code) –Prog file: File03.java –Input data file inp1: np2 How to run the program: Right click on both links and save in a scratch directory To compile: javac File03.java To run: java File03

Programming example 3: compute the average of (floating point) data in a data file (cont.) Example run: Input file inp3: Output of the program: Average = 4.4