OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Advertisements

CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Evan Korth Scanner class Evan Korth NYU. Evan Korth Java 1.5 (5.0)’s Scanner class Prior to Java 1.5 getting input from the console involved multiple.
Lecture 3 Java Basics Lecture3.ppt.
21-Jun-15 Simple Text I/O. java.util.Scanner Java finally has a fairly simple way to read input First, you must create a Scanner object To read from the.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.
***** SWTJC STEM ***** Chapter 3-1 cg 36 Java Class Libraries & API’s A class library is a set of classes that supports the development of programs. Java.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 2 *Includes materials provided by George Koutsogiannakis and Matt Bauer 1.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Topics Instance variables, set and get methods Encapsulation
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 6_1 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 116 Object Oriented Programming II Lecture 11 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Today… StringTokenizer class. Method Overloading. Catching Exceptions (and what they are!). Start Pointers and Aliasing. Winter 2016CMPE212 - Prof. McLeod1.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction to programming in java
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Some Eclipse shortcuts
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS
Building Java Programs
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
Console Input and Output
User input We’ve seen how to use the standard output buffer
Building Java Programs
Building Java Programs
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Building Java Programs
OBJECT ORIENTED PROGRAMMING II GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II GEORGE KOUTSOGIANNAKIS
Building Java Programs
Fundamental Error Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
CS201 Fall 2016 George Koutsogiannakis
Building Java Programs
Review for Midterm 3.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS Copyright: SPRING 2017 Illinois Institute of Technology/George Koutsogiannakis

OOP Review In previous lectures we discussed: User defined template classes Default constructor/ non default constructor(s). Accessor mutator methods. toString method. Equals method Other methods as required by the specification. Client classes How to use a static instance variable. Receiving inputs from user via command line and via the scanner object Note: You must bring your text to the lectures

OOP Review Today we want to review: Using the scanner object to read text files. Scope of variables within the class. Formatting Numbers.

Reading Text Files with Scanner Object We need the services of the java.io package and specifically two classes out of that package: File class IOException class Therefore we need to import those library classes import java.io.File; import java.io.IOException; Note: Alternatively one can import all the library classes out of package java.io by typing: import java.io.*;

Reading Text Files with Scanner Object Trying to open a file for reading (or writing) can cause problems (called exceptions) for various reasons of which some are: File does not exist. File name was misspelled File is corrupted. The part of the O.S. that finds files and opens them for reading and writing does not work. The java program we wrote has other problems. The java run time environment is corrupted Other reasons Therefore , we need to catch the exception ,if it happens, so that we don’t crash our program or the system.

Reading Text Files with Scanner Object Within the method that needs to open the file for reading write the following code: try { //code to open the file for reading and //capturing the read items goes here. } catch (IOException ioe) System.out.println(“Something went wrong”);

Reading Text Files with Scanner Object try and catch are keywords Inside the try block: try { File myfile = new File(“NameOfTextFile.txt”); Scanner scan= new Scanner(myfile); //The above code tells the system to find the file we are //looking for and associates the scanner object with that file. //Other code } catch (IOException ioe) System.out.println(“Error Occurred”);

Reading Text Files with Scanner Object Continue inside the try block by creating a loop that keeps reading data until there is no more data to be read. The scanner class has methods that allow us to read one String at a time or one line at a time (as one String). Look up the scanner class and its methods in the API.

Scanner Class hasNext Method This method detects the end of the input values one String at a time (one token). The hasNext method eliminates the need for a priming read because the method looks ahead for input. An IOException may be generated if we encounter problems reading the file. Java requires us to acknowledge that these exceptions may be generated. Note that there is another method called hasNextLine() which returns a boolean and can sense the end of data line by line. Return type Method name and argument list Boolean hasNext( ) returns true if there is more data to read; returns false when the end of the file is reached

Scanner Class hasNext… Methods Each method returns true if the next token in the input stream can be interpreted as the data type requested, and false otherwise. Return type Method name and argument list boolean hasNextInt( ) hasNextDouble( ) hasNextFloat( ) hasNextByte( ) hasNextShort( ) hasNextLong( ) hasNextBoolean( ) hasNext( )

Example Reading From File import java.io.File; import java.io.IOException; Import java.util.Scanner; public class ReadFile { public static void main(String[] args) { String str=“ “; int count=0; try { File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile); while(scan.hasNextLine()) str=scan.nextLine(); System.out. println(str); count++; // Note that if we want the individual Strings (tokens) inside each line, we need to use the StringTokenizer object to tokenize the line read during each iteration!!!! } } //end of try block of code!!!!!! catch(IOException ioe) { System.out.println(“The file can not be read”); } System.out.println(“The number of strings tokens read is:”+count);

StringTokenizer In the previous example we captured one line of data at a time, from the text file. The String str has the value of the entire line during each cycle in the while loop (its value changes to the next line during the next cycle). Now, we may be interested in the individual Strings that make up the entire line. Therefore when we capture the line we may want to break it up into individual tokens. To do that we would need to create another loop inside the loop while(scan.hasNextLine()). The reason for that is that we don’t know how many tokens are in one line (presumably the programmer does not know the content of the text file that his/her program is reading).

StringTokenizer Modifying the program for the StringTokenizer: First at the top we need to import the library package java.util which contains the StringTokenizer class. Then we modify the while loop as follows: while(scan.hasNextLine()) { str=scan.nextLine(); StringTokenizer strtok=new StringTokenizer(str, “,”); while(strtok.hasMoreTokens()) String tokenstr=strtok.nextToken(); //Now, do what you want with the String tokenstr. You may have to //parse it to another data type depending on what data type you expect. } System.out. println(str); count++;

StringTokenizer Look up the StringTokenizer class in the API NOW. Questions: What does the parameter count measure? What is the meaning of the “ , ” in the constructor of StringTokenizer? Can we have any delimiter? What about using space as a delimiter?

Class Scope In the previous example the String str was declared at the top of the main method. Therefore we say that the String str has method scope. That means that the value held by the identifier str can be seen anywhere from within the method. If, for example, we had declared str inside the while loop :

Class Scope while(scan.hasNextLine()) { String str=scan.nextLine(); System.out. println(str); count++; // Note that if we want the individual Strings (tokens) inside each line, we need to use the StringTokenizer object to tokenize the line read during each iteration!!!! } Then trying to access the value of str outside the while loop would had caused an error, because the variable’ s str scope is limited to the while loop in this case The same problem arises if we declared String str at the top of the try block and then try to access it outside the try block:

Class Scope try { String str=“ “; File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile); while(scan.hasNextLine()) str=scan.nextLine(); System.out. println(str); count++; // Note that if we want the individual Strings (tokens) inside each line, we need to use the StringTokenizer object to tokenize the line read during each iteration!!!! } Trying to access str outside the try block will cause an error. The scope of str is limited within the try block. Note that accessing str inside the while loop is O.K. because the while loop is part of the try block.

Class Scope What if we declared the String str outside the main method? public class ReadFile { String str=“ “; public static void main(String[] args) { int count=0; try { File myFile=new File(“text.txt”); Scanner scan=new Scanner(myFile); ……………………………………………… }// end of main method public static void anotherMethod() { } }//end of class

Class Scope Notice that in this case we have included another method in the class besides the main. Since the String str is declared outside any method but inside the class , we say that the variable str has class scope: That means that its value can be seen and it is accessible by any method in the class!!

Formatting Numbers In this lecture we would discuss only two types of formatting: Formatting a double data type to restrict the number of decimal points. Formatting a decimal number to convert it to a particular currency like US dollars. The first action is done with library class: DecimalFormat from package java.text (must import java.text.DecimalFormat)

Formatting Numbers Create an object of DecimalFormat and in the constructor define the pattern of decimal points as a String DecimalFormat df=new DecimalFormat(“0.00”); The object df can convert double data types to the accuracy of only two decimal points in this example pattern. Suppose we have the decimal data type double mydoubletype The code below converts the data type mydoubletype into a new data type of double type but with a precision of only two decimal points: double newdoubletype= df.format(mydoubletype);

Formatting Numbers The conversion to currency is done with library class NumberFormat of package java.text (import java.text.NumberFormat;) For US dollars: create an object like this: NumberFormat form=NumberFormat.getCurrencyInstance(); Use the object form as follows: String strversionofdouble=form.format(mydoublenumber); Notice that the double number held by identifier mydouublenumber is converted into two decimal points and the $ sign is placed in front of it. It then it gets assigned to a String type. If we want the String strversionofdouble converted back to a double we need to parse it