Slide3.1_2009 - Module 3.1 Module Strings and Text I/O Strings EE3206/EE5805 Java Programming and Applications 1 Intended Learning Outcomes To use

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 3.1 Module Strings and Text I/O Strings EE3206/EE5805 Java Programming and Applications 1 Intended Learning Outcomes To use the String class to process fixed strings. String To use the Character class to process a single character. Character To use the StringBuffer class to process flexible strings. StringBuffer class To learn how to pass strings to the main method from the main method command line. command To discover file properties, delete and rename files using the File class. File To write data to a file using the PrintWriter class. PrintWriter class. To read data from a file using the Scanner class. Scanner To divide string into tokens using StringTokenizer StringTokenizer EE3206/EE5805 Java Programming and Applications 2 The String Class The String Constructing a String: Constructing String message = “Welcome to Java”; String message = new String("Welcome to Java“); String String s = new String(); String Common string opertations opertations Obtaining String length Retrieving Individual Characters in a string Retrieving String Concatenation (concat) String Substrings (substring(index), substring(start, end)) Substrings Comparisons (equals, compareTo) compareTo String Conversions String Finding a Character or a Substring in a String Finding Conversions between Strings and Arrays Conversions Converting Characters and Numeric Values to Strings Converting EE3206/EE5805 Java Programming and Applications 3 Constructing Strings String newString = new String(stringLiteral); newString new String(stringLiteral Example: String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: initializer Example: String message = "Welcome to Java"; EE3206/EE5805 Java Programming and Applications 4 Strings Are Immutable A String object is immutable; iits contents cannot be changed. Does the following String immutable ts code change the contents of the string? String s = "Java"; String s = "HTML"; After executing String s = "Java"; s : String String object for "Java" After executing s = "HTML"; s : String String object for "Java" This string object is now unreferenced Contents cannot be changed : String String object for "HTML" EE3206/EE5805 Java Programming and Applications 5 Finding String Length and Characters Finding string length using the length() method: length() message = "Welcome"; message.length() (returns 7) message.length() (returns Using charAt(int) method to retrieve individual character. charAt(int Do not use message[0] message[0] Use message.charAt(index) message.charAt(index Index starts from 0 0 W 1 e 2 l 3 c 4 o 5 m 6 e 7 8 t 9 o 10 11 12 13 1 4 J a v a Indices message message.charAt(0) message.length() is 15 message.charAt(14) 6 EE3206/EE5805 Java Programming and Applications String Concatenation Use concat method or + operator to connect two strings: concat or operator Example: String s3 = s1.concat(s2); same as String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 s1 same as same (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5); EE3206/EE5805 Java Programming and Applications 7 Extracting Substrings You can extract a single character from a string using the charAt charAt method. You can also extract a substring from a string using the substring method in the String class. method String class. substring(start, end) returns a string from (start) to (end - 1). substring(start end) String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML"; Indices message 0 W 1 e 2 l 3 c 4 o 5 m 6 e 7 8 t 9 o 10 1 1 1 2 1 3 14 J a v a message.substring(0, 11) message.substring(11) 8 EE3206/EE5805 Java Programming and Applications String Comparisons Use equals method or == operator to compare strings equals or == String s1 = new String(“Welcome”); String String( String s2 = new String(“Welcome”); String String( if (s1.equals(s2)){ // true if // // s1 and s2 have the same contents // same } if (s1 == s2) { // false // s1 and s2 have the same reference // same } EE3206/EE5805 Java Programming and Applications 9 String Comparisons String class implements Comparable interface String compareTo(Object object) compareTo(Object String String String String String s1 s2 s3 s4 s5 = = = = = "Welcome"; "welcome"; "wElcome"; "Welcomes"; "Welcome"; // // // // // // ascii ascii ascii ascii ascii ascii of of of of of of ‘W ’ ‘w ’ ‘E ’ is is is is 87 119 69, ‘e’ is 101 System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s3)); System.out.println(s1.compareTo(s4)); System.out.println(s4.compareTo(s1)); System.out.println(s5.compareTo(s1)); // // // // // // (W-w) returns -32 w) (e-E) returns 32 returns -1 returns 1 returns 0 EE3206/EE5805 Java Programming and Applications 10 String Conversions The contents of a string cannot be changed once the string is created. But The eated. you can convert a string to a new string using the following methods. you hods. The methods return a modified new string while the original string remains new while unchange. unchange toLowerCase() toLowerCase toUpperCase() toUpperCase trim() trim() replace(oldChar, newChar) replace(oldChar newChar // remove leading and trailing spaces Example Example String s1 = “Hello World”; String String s2 = s1.toLowerCase(); System.out.println(s1 + ‘ ’ + s2); System.out.println(s1 // Hello World hello world EE3206/EE5805 Java Programming and Applications 11 Finding the index of Finding a Character or a Substring Character "Welcome elcome "Welcome "Welcome "Welcome "Welcome "Welcome "Welcome "Welcome "Welcome "Welcome "Welcome to to to to to to to to Java".indexOf('W') returns 0. Java".indexOf('W Java".indexOf('x') returns -1. Java".indexOf('x returns Java".indexOf('o', 5) returns 9. Java".indexOf("come") returns 3. Java".indexOf("come Java".indexOf("Java", 5) returns 11. Java Java".indexOf("java", 5) returns -1. Java".indexOf("java returns Java".lastIndexOf('a') returns 14. Jav Search from index 5 EE3206/EE5805 Java Programming and Applications 12 Convert Character and Numbers to Strings The String class provides several static valueOf() methods for valueOf() converting a character, an array of characters, and numeric values to converting es strings. These methods have the same name valueOf with different argument valueOf with types char, char, double, long, int, and float. int and For example, to convert a double value to a string, use String.valueOf(5.44). The return value is a string representation of String.valueOf(5.44). of “5.44”. EE3206/EE5805 Java Programming and Applications 13 The Character Class The Character Character charObject = new Character('b'); charObject charObject.compareTo(new Character('a'')); )); charObject.compareTo(new Character('b'')); )); charObject.compareTo(new Character('c'')); )); charObject.compareTo(new Character('d''); ); charObject.equals(new Character('b'')); )); charObject.equals(new Character('d'')); )); //returns 1 //returns //returns 0 //returns //returns -1 //returns –2 //returns true //returns //returns false //returns java.lang.Character +Character(value: char) +charValue(): char +compareTo(anotherCharacter: Character): int Constructs a character object with char value Returns the char value from this object Compares this character with another +equals(anotherCharacter: Character): boolean Returns true if this character equals to another +isDigit(ch: char): boolean Returns true if the specified character is a digit +isLetter(ch: char): boolean +isLetterOrDigit(ch: char): boolean +isLowerCase(ch: char): boolean +isUpperCase(ch: char): boolean +toLowerCase(ch: char): char Returns true if the specified character is a letter Returns true if the character is a letter or a digit Returns true if the character is a lowercase letter Returns true if the character is an uppercase letter Returns the lowercase of the specified character 14 EE3206/EE5805 Java Programming and Applications +toUpperCase(ch: char): char Returns the uppercase of the specified character Example: Example: Counting Each Letter in a String Counting This example gives a program that counts the number of This occurrence of each letter in a string. Assume the letters are not case-sensitive. are CountEachLetter Run EE3206/EE5805 Java Programming and Applications 15 The StringBuffer Class The StringBuffer The StringBuffer class is an alternative to the StringBuffer class String class. In general, a StringBuffer can be used String class. StringBuffer can wherever a string is used. StringBuffer iis mutable, hence more flexible than StringBuffer s mutable hence String. String The value of a String object is fixed once the string is created. String object You can add, insert, or append new contents into a string buffer. buffer. EE3206/EE5805 Java Programming and Applications 16 java.lang.StringBuffer +StringBuffer() +StringBuffer(capacity: int) +StringBuffer(str: String) +append(data: char): StringBuffer +append(data: char, offset: int, len: int): StringBuffer +append(v: aPrimitiveType): StringBuffer +append(str: String): StringBuffer +capacity(): int +charAt(index: int): char +delete(startIndex: int, endIndex: int): StringBuffer +deleteCharAt(int index): StringBuffer +insert(index: int, data: char, offset: int, len: int): StringBuffer +insert(offset: int, data: char): StringBuffer +insert(offset: int, b: aPrimitiveType): StringBuffer +insert(offset: int, str: String): StringBuffer +length(): int +replace(int startIndex, int endIndex, String str): StringBuffer +reverse(): StringBuffer +setCharAt(index: int, ch: char): void +setLength(newLength: int): void +substring(startIndex: int): String Constructs an empty string buffer with capacity 16 Constructs a string buffer with the specified capacity Constructs a string buffer with the specified string Appends a char array into this string buffer Appends a subarray in data into this string buffer Appends a primitive type value as string to this buffer Appends a string to this string buffer Returns the capacity of this string buffer Returns the character at the specified index Deletes characters from startIndex to endIndex Deletes a character at the specified index Inserts a subarray of the data in the array to the buffer at the specified index Inserts data to this buffer at the position offset Inserts a value converted to string into this buffer Inserts a string into this buffer at the position offset Returns the number of characters in this buffer Replaces the characters in this buffer from startIndex to endIndex with the specified string Reveres the characters in the buffer Sets a new character at the specified index in this buffer Sets a new length in this buffer Returns a substring starting at startIndex 17 EE3206/EE5805 +substring(startIndex: int, endIndex: int): String Java Programming and Applications Returns a substring from startIndex to endIndex StringBuffer Constructors public StringBuffer() StringBuffer No characters, initial capacity 16 characters. No public StringBuffer(int length) StringBuffer(int No characters, initial capacity specified by the length length argument. public StringBuffer(String str) StringBuffer(String Represents the same sequence of characters Represents as the string argument. The initial capacity of the as string argument. string buffer is 16 plus the length of the string argument. EE3206/EE5805 Java Programming and Applications 18 Appending New Contents into a String Buffer StringBuffer strBuf = new StringBuffer(); new StringBuffer strBuf.append("Welcome"); strBuf.append(' '); strBuf.append("to"); strBuf.append(' '); strBuf.append("Java"); // strBuf contains “Welcome to Java” // strBuf contains System.out.println(strBuf); EE3206/EE5805 Java Programming and Applications 19 Passing Parameters to Main Method Method 1 - You can call a regular method by passing actual parameters. Can you pass arguments to main? Of course, yes. For example, the main method in class B is invoked by a method in A, as shown below: public class A { public static void main(String args) { String strings = {"New York", "Boston", "Atlanta"}; B.main(strings); } } class B { public static void main(String args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } } Method 2 (command line) - In the main method below, you can get the arguments from args[0], args[1], ..., args[n], which corresponds to arg0, arg1, ..., argn in the command line. class TestMain { class TestMain public static void main(String args) { public args } C:\> java TestMain arg0 arg1 arg2 ... argn java TestMain arg0 argn ... } EE3206/EE5805 Java Programming and Applications 20 Example: Example: Using Command-Line Parameters Using Objective: Write a program that will perform binary operations on integers. The program receives three parameters: an operator and two integers. parameters: java Calculator 2 + 3 Calculator java Calculator 2 - 3 java Calculator 2 / 3 java Calculator 2 x 3 Run EE3206/EE5805 Java Programming and Applications 21 The File Class The File class is intended to provide an abstraction that File class deals with most of the machine-dependent complexities machine complexities of files and path names in a machine-independent fashion. machine fashion. Different operating systems use different file systems. Different Data structures of file are different Data Support filename formats are different File properties are different File The File class is a wrapper class for the file name and its directory path. You can obtain file properties and manipulate file through File class. File EE3206/EE5805 Java Programming and Applications 22 java.io.File +File(pathname: String) Creates a File object for the specified pathname. The pathname may be a directory or a file. +File(parent: String, child: String) Creates a File object for the child under the directory parent. child may be a filename or a subdirectory. +File(parent: File, child: String) Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string. +exists(): boolean Returns true if the file or the directory represented by the File object exists. +canRead(): boolean +canWrite(): boolean +isDirectory(): boolean +isFile(): boolean +isAbsolute(): boolean +isHidden(): boolean Returns true if the file represented by the File object exists and can be read. Returns true if the file represented by the File object exists and can be written. Returns true if the File object represents a directory. Returns true if the File object represents a file. Returns true if the File object is created using an absolute path name. Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character '.'. Returns the complete absolute file or directory name represented by the File object. Returns the same as getAbsolutePath() except that it removes redundant names, such as "." and "..", from the pathname, resolves symbolic links (on Unix platforms), and converts drive letters to standard uppercase (on Win32 platforms). Returns the last name of the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getName() returns test.dat. Returns the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat. Returns the complete parent directory of the current directory or the file represented by the File object. For example, new File("c:\\book\\test.dat").getParent() returns c:\book. Returns the time that the file was last modified. Deletes this file. The method returns true if the deletion succeeds. Renames this file. The method returns true if the operation succeeds. +getAbsolutePath(): String +getCanonicalPath(): String +getName(): String +getPath(): String +getParent(): String +lastModified(): long +delete(): boolean +renameTo(dest: File): boolean EE3206/EE5805 Java Programming and Applications 23 Example: Using the File Class Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. Sample run of the program on Windows Sample run on Unix. TestFileClass Run EE3206/EE5805 Java Programming and Applications 24 Text I/O (Input/Output) A File object encapsulates the properties of a file or a path, File object but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. The objects contain the methods for reading/writing data from/to a file. This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and Scanner and PrintWriter classes. PrintWriter EE3206/EE5805 Java Programming and Applications 25 Writing Data Using PrintWriter Writing PrintWriter java.io.PrintWriter +PrintWriter(filename: String) +print(s: String): void +print(c: char): void +print(cArray: char): void +print(i: int): void +print(l: long): void +print(f: float): void +print(d: double): void +print(b: boolean): void Also contains the overloaded println methods. Also contains the overloaded printf methods. Creates a PrintWriter for the specified file. Writes a string. Writes a character. Writes an array of character. Writes an int value. Writes a long value. Writes a float value. Writes a double value. Writes a boolean value. A println method acts like a print method; additionally it prints a line separator. The line separator string is defined by the system. It is \r\n on Windows and \n on Unix. The printf method was introduced in §3.6, “Formatting Console Output and Strings.” WriteData Run EE3206/EE5805 Java Programming and Applications 26 Reading Data Using Scanner Reading Scanner java.util.Scanner +Scanner(source: File) +Scanner(source: String) +close() +hasNext(): boolean +next(): String +nextByte(): byte +nextShort(): short +nextInt(): int +nextLong(): long +nextFloat(): float +nextDouble(): double +useDelimiter(pattern: String): Scanner Creates a Scanner that produces values scanned from the specified file. Creates a Scanner that produces values scanned from the specified string. Closes this scanner. Returns true if this scanner has another token in its input. Returns next token as a string. Returns next token as a byte. Returns next token as a short. Returns next token as an int. Returns next token as a long. Returns next token as a float. Returns next token as a double. Sets this scanner’s delimiting pattern. ReadData Run EE3206/EE5805 Java Programming and Applications 27 The StringTokenizer Class A string can be broken down into a number of tokens based on a delimiter. The tokens are then parsed one by one orderly. The following string can be seen as three tokens delimited by commas: following one,two,three one,two,three java.util.StringTokenizer +StringTokenizer(s: String) Constructs a string tokenizer for the string. +StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string with the specified delimiters. String) +StringTokenizer(s: String, delimiters: Constructs a string tokenizer for the string with the delimiters and returnDelims. String, returnDelimiters: boolean) +countTokens(): int +hasMoreTokens(): boolean +nextToken(): String Returns the number of remaining tokens. Returns true if there are more tokens left. Returns the next token. +nextToken(delimiters: String): String Returns the next token using new delimiters. EE3206/EE5805 Java Programming and Applications 28 Examples 1 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s); new StringTokenizer(s System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays The total number of tokens is 3 Java is cool. EE3206/EE5805 Java Programming and Applications 29 Examples 2 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s, "ac"); new StringTokenizer(s System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays The total number of tokens is 4 J v is ool. All characters in the argument are delimiters EE3206/EE5805 Java Programming and Applications 30 Examples 3 String s = "Java is cool."; StringTokenizer tokenizer = new StringTokenizer(s, "ac", true); new StringTokenizer(s "ac", System.out.println("The total number of tokens is " + tokenizer.countTokens()); while (tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); The code displays Delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters The total number of tokens is 7 J a v a is c ool. 31 EE3206/EE5805 Java Programming and Applications The Scanner Class The delimiters are single characters in StringTokenizer. You may use The StringTokenizer You the Scanner class to specify a word as a delimiter. Scanner class specify String s = "Welcome to Java! Java is fun! Java is cool!"; Scanner scanner = new Scanner(s); scanner.useDelimiter("Java"); while (scanner.hasNext()) System.out.println(scanner.next()); Creates an instance of Scanner for the Creates Scanner for string. Sets “Java” as a delimiter. as hasNext() returns true if there are still hasNext returns more tokens left. more The next() method returns a The next() method token as a string. Output Welcome to Welcome ! is fun! is cool! EE3206/EE5805 Java Programming and Applications 32 Scanning Primitive Type Values If a token is a primitive data type value, you can use the methods nextByte(), If ds nextByte nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to nextShort nextInt nextLong nextFloat nextDouble or nextBoolean to obtain it. For example, the following code adds all numbers in the string. Note that the delimiter is whitespace by default. whitespace i.e. Space, Tab , Line Feed, Carriage Return Carriage String s = "1 2 3 4"; Scanner scanner = new Scanner(s); int sum = 0; while (scanner.hasNext()) sum += scanner.nextInt(); sum scanner.nextInt System.out.println("Sum is " + sum); EE3206/EE5805 Java Programming and Applications 33 Console Input Using Scanner Another important application of the Scanner class is to read input from the console. Another Scanner class For example, the following code reads an int value from the keyboard: int value System.out.print("Please enter an int value: "); int Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); scanner.nextInt An instance of InputStream NOTE: NOTE: StringTokenizer can specify several single characters as delimiters. StringTokenizer can Scanner can use a single character or a word as the delimiter. Scanner can So, if you need to scan a string with multiple single characters as delimiters, use So, as StringTokenizer. If you need to use a word as the delimiter, use Scanner. StringTokenizer If Scanner EE3206/EE5805 Java Programming and Applications 34 ...
View Full Document

This note was uploaded on 04/20/2010 for the course ELECTRONIC EE3206 taught by Professor Tingchiwang during the Spring '10 term at École Normale Supérieure.

Ask a homework question - tutors are online