Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.

Similar presentations


Presentation on theme: "Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17."— Presentation transcript:

1 Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17

2 The String Class A class in the Java Class Library A class in the Java Class Library Part of the java.lang package Part of the java.lang package NOTE: java.lang is the core package of the basic Java classes, including: NOTE: java.lang is the core package of the basic Java classes, including: String String System System Object Object Math Math lots of others lots of others Strings are immutable (values cannot be changed once created). Another string-like object that can be changed is StringBuffer. Strings are immutable (values cannot be changed once created). Another string-like object that can be changed is StringBuffer.

3 Initializing a String The formal way: The formal way: String s = new String(“the string value”); String s = new String(“the string value”); String() is a special method called a constructor, which is called to create and initialize an object (more about constructors when we do object-oriented programming) String() is a special method called a constructor, which is called to create and initialize an object (more about constructors when we do object-oriented programming) This creates a new instance of the String class in the heap This creates a new instance of the String class in the heap A shortcut way…forget using new: A shortcut way…forget using new: String s = “the string value”; String s = “the string value”; This does not instantiate a new string. Instead it points to a constant string in the constants pool of memory. This does not instantiate a new string. Instead it points to a constant string in the constants pool of memory. NOTE: like with any other object instantiation, the variable s is NOT a String object. It is a REFERENCE to a String object. The String object itself is on the heap. s points at it.

4 Comparing Strings Suppose you have two string references, s1 and s2. Suppose you have two string references, s1 and s2. If you do the following: If you do the following: if (s1 == s2) if (s1 == s2) This tests to see if the variables s1 and s2 are pointing to the same string object. This tests to see if the variables s1 and s2 are pointing to the same string object. This is NOT testing to see if the values in two different strings are identical. This is NOT testing to see if the values in two different strings are identical. To test for equality of value (not equality of reference), you use this syntax: To test for equality of value (not equality of reference), you use this syntax: if (s1.equals(s2)) if (s1.equals(s2)) This will test to see if two different strings have the same value. This will test to see if two different strings have the same value. equals is an instance method of the String class equals is an instance method of the String class compareTo is another useful comparison method of the String class. compareTo is another useful comparison method of the String class. See also equalsIgnoreCase and compareToIgnoreCase See also equalsIgnoreCase and compareToIgnoreCase

5 Useful String Instance Methods toUpperCase() – converts a string to upper case. Returns a String. toUpperCase() – converts a string to upper case. Returns a String. toLowerCase() – converts a string to lower case. Returns a String. toLowerCase() – converts a string to lower case. Returns a String. substring(int start, int end) – returns the String starting a start, ending at end-1. (end is optional). substring(int start, int end) – returns the String starting a start, ending at end-1. (end is optional). charAt(int position) – returns the char value at the designated position. charAt(int position) – returns the char value at the designated position. length() – returns the number of characters in the string length() – returns the number of characters in the string There are lots more useful methods. Check out the String class in the Java documentation and in chapter 7 of Liang. There are lots more useful methods. Check out the String class in the Java documentation and in chapter 7 of Liang.

6 An Example Using String Methods

7 HeapFrame Stack main’s frame args s1s2 s1 and s2 are equal. They point to the same object, which is a literal string located in the constants pool. String Object value a string String Object value another string Constants Pool Constants pool is a memory location that contains all constants and literals of the application

8 HeapFrame Stack main’s frame args s1s2 String Object value a string String Object value a string s1 and s2 are NOT equal. They point to different objects. But, the contents of the strings pointed at by s1 and s2 are equal. String Object value a string String Object value another string Constants Pool

9 HeapFrame Stack main’s frame args s1s2 String Object value a string String Object value a string String Object value a string String Object value another string Constants Pool S2 is changed to point to the other literal string in the constants pool. The value of the old string pointed at by s2 does not change. Eventually, this string will be discarded by the garbage collector.

10 HeapFrame Stack main’s frame args s1s2 String Object value a string String Object value a string String Object value a string String Object value another string Constants Pool S1 is changed to point to the same string that s2 points at. The value of the old string pointed at by s1 does not change. Eventually, this string will be discarded by the garbage collector.

11 Lesson Learned Don’t expect s1==s2 to work the way you want it to. This will be true ONLY if the references are pointing to the same object Don’t expect s1==s2 to work the way you want it to. This will be true ONLY if the references are pointing to the same object To test for equality of VALUE, use s1.equals(s2), or another similar method. To test for equality of VALUE, use s1.equals(s2), or another similar method.

12 Using other Methods in the Example Instance method toUpperCase called with respect to the string object pointed at by s1. toUpperCase creates a new String object and returns a reference to that new object, which contains the same value as the string of s1, but entirely in upper case. Instance method substring called with respect to the string object pointed at by s1. substring creates a new String object and returns a reference to that new object, which contains the characters from position 3 to position 5 of the string pointed at by s1.

13 Using other Methods in the Example substring returns a reference to a new String object toUpperCase called with respect to the String object returned from substring NOTE: cascading method calls

14 Using StringTokenizer Useful for breaking a string into individual tokens. Useful for breaking a string into individual tokens. A token is a single unit of the string (a substring). A token is a single unit of the string (a substring). Tokens are separated by delimiters Tokens are separated by delimiters Default delimiters are space, tab (\t), new line (\n), and carriage return (\r) Default delimiters are space, tab (\t), new line (\n), and carriage return (\r) You can specify your own delimiters if you want You can specify your own delimiters if you want

15 StringTokenizer Class Contained in the java.util package (need to import this package) Contained in the java.util package (need to import this package) Constructors: Constructors: StringTokenizer(String str) StringTokenizer(String str) StringTokenizer(String str, String delim) StringTokenizer(String str, String delim) StringTokenizer(String str, String delim, boolean returnDelimiters) StringTokenizer(String str, String delim, boolean returnDelimiters) Important methods Important methods countTokens() – returns the number of tokens in the string countTokens() – returns the number of tokens in the string hasMoreTokens() – returns true or false hasMoreTokens() – returns true or false nextToken() – returns the next token in the string nextToken() – returns the next token in the string Note: a constructor is a method that is invoked when an object is instantiated (created)

16 Example from my own notes

17 Import the package Instantiate the tokenizer object Find out how many tokens there are Get each token Instantiate the tokenizer object with special delimiters Instantiate the tokenizer object with special delimiters, here the delimters are tokens

18 output

19

20

21 Writing and Reading Text Files Writing Writing Create a File instance Create a File instance Create a PrintWriter to enable writing Create a PrintWriter to enable writing Use the PrintWriter class’s print() or println() method to write to the file Use the PrintWriter class’s print() or println() method to write to the file Use the PrintWriter class’s flush() method to force output from memory buffer to the file Use the PrintWriter class’s flush() method to force output from memory buffer to the file Reading: Reading: Create a File instance Create a File instance Create a Scanner instance to enable reading Create a Scanner instance to enable reading Use Scanner’s various methods to read Use Scanner’s various methods to read hasNext() determines if there is anything more to read hasNext() determines if there is anything more to read Next(), nextDouble(), nextInt(), etc. Next(), nextDouble(), nextInt(), etc. To use the file i/o examples, put the text files in folder c:\temp

22 The File Class Used to internally represent an external file Used to internally represent an external file Creating an instance of the File will open the associated file: Creating an instance of the File will open the associated file: File myfile = new File(“filename”); File myfile = new File(“filename”); Files can then be used by: Files can then be used by: Scanner – for input Scanner – for input PrintWriter – for output PrintWriter – for output

23 The PrintWriter Class Class that supports writing to an output stream Class that supports writing to an output stream Note: System.out is an output stream, files can also be considered to be streams, and PrintWriter is a class for writing to output streams Note: System.out is an output stream, files can also be considered to be streams, and PrintWriter is a class for writing to output streams

24 What is a STREAM? A data structure that represents the flow of data between RAM and an external device. A data structure that represents the flow of data between RAM and an external device. Example: Example: Streams for input and output devices (e.g. keyboard, screen) Streams for input and output devices (e.g. keyboard, screen) Streams for data files (on disk) Streams for data files (on disk) Streams for sockets (network connections) Streams for sockets (network connections)

25 Write example from textbook

26 Read example from textbook hasNext() checks for EOF

27 Exceptions In previous examples, the main method throws exceptions. In previous examples, the main method throws exceptions. This means the caller of the method is responsible for handling the exception…not very elegant This means the caller of the method is responsible for handling the exception…not very elegant Instead, it is better if the exceptions generated are caught…following example shows this. Instead, it is better if the exceptions generated are caught…following example shows this.

28 Read example from my samples

29 Input file Output file

30 Instantiate File and Scanner objects for input

31 Read/Write example from my samples Instantiate File and PrintWriter objects for output

32 Here I use an outer loop to check for EOF, and to read the label and initialize the tot for summing Read/Write example from my samples

33 I use the inner loop to to read all the numbers from the line and sum them together. Note that hasNextDouble() checks to see if the next token is a number. Read/Write example from my samples

34 Note that the same methods print() and println() can be used for System.out (the standard output display stream) and for the PrintWriter for file output. Read/Write example from my samples

35 Make sure to close the output file after done writing…this forces any data remaining in the memory buffer to be written to the file Read/Write example from my samples

36 Exception Handling Stream input requires use of Exception handling Stream input requires use of Exception handling standard try/catch format OR standard try/catch format OR throws IOException in methods throws IOException in methods

37 Exception Handling Using try and catch try{……..} catch (ExceptionType e){ ……..} If code within the try block causes an error, the program will automatically branch to the catch block

38 Read/Write example from my samples Any code that could cause an exception should be placed in the try portion. If an exception occurs, the program will immediately branch to the catch section The Exception’s toString() method gives the specific error message.

39 Reading Full Lines and Using StringTokenizer An alternative to reading one token at a time from the file is to read an entire line, then use StringTokenizer to break it up into tokens An alternative to reading one token at a time from the file is to read an entire line, then use StringTokenizer to break it up into tokens

40 Using StringTokenizer with Files StrngTokenizer can be used to divide the line of text into separate data items StrngTokenizer can be used to divide the line of text into separate data items You can use Wrapper classes to convert strings into numeric data for arithmetic processing You can use Wrapper classes to convert strings into numeric data for arithmetic processing Integer.parseInt(String) – converts a string into an int Integer.parseInt(String) – converts a string into an int Double.parseDouble(String) – converts a string into a double Double.parseDouble(String) – converts a string into a double

41

42 To use StringTokenizer, you must import the java.util package, and for File you need java.io.

43 To create a string tokenizer, call the StringTokenizer constructor, passing the string to tokenize as an argument.

44 The hasMoreTokens method returns true or false, depending on if there are more tokens in the string.

45 The nextToken method returns a string, which is the next token in the source string.

46 Here, I am checking to see if the character of the token is a number (a digit).

47 The parseDouble method converts the string into a number.

48 Program’s output


Download ppt "Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17."

Similar presentations


Ads by Google