Presentation is loading. Please wait.

Presentation is loading. Please wait.

OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS

Similar presentations


Presentation on theme: "OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS"— Presentation transcript:

1 OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
CS 201 OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS Copyright: SPRING Illinois Institute of Technology/George Koutsogiannakis

2 OOP Review In previous lectures we discussed: Using the Scanner Object
Using the StringTokenizer object Using Arrays Reading data off text files Note: You must bring your text to the lectures

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

4 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.*;

5 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.

6 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”);

7 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”);

8 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.

9 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

10 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( )

11 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);

12 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).

13 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++;

14 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?

15 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 :

16 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:

17 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.

18 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

19 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!!

20 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)

21 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);

22 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


Download ppt "OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS"

Similar presentations


Ads by Google