http www csie nctu edu twtsaiwnoop Programming in

  • Slides: 56
Download presentation
http: //www. csie. nctu. edu. tw/~tsaiwn/oop/ Programming in Java String and String Parser java.

http: //www. csie. nctu. edu. tw/~tsaiwn/oop/ Programming in Java String and String Parser java. util. * -- Vector, Stack, Hash. Table… 蔡文能 交通大學資訊 程學系 tsaiwn@csie. nctu. edu. tw 交通大學資訊 程學系

Java String and Parser Agenda Character, String class and the String. Buffer class Character

Java String and Parser Agenda Character, String class and the String. Buffer class Character in a String -- char. At(int i) Sub. String in a String – substring(int p, int n) More String/String. Buffer methods Type Wrappers again Utilities -- java. util. * - String. Tokenizer - Vector, Stack, Hash. Table 交通大學資訊 程學系 蔡文能 第 2頁

Java String and Parser Consider how to read a number? In C Language: -

Java String and Parser Consider how to read a number? In C Language: - scanf with %d format (%f for float, %lf for double) May cause program down due to strange input May forget to pass address of variable to scanf - Better way Read it into program as a string ( how ? ) - gets(buf); /* not good enough */ - fgets(buf, sizeof(buf), stdin); /* buf is a char array */ Then, use sscanf to scan that string; or use the following utility functions: - atol, atof, strtol, strtod, strtok, strsep What about in Java ? 交通大學資訊 程學系 蔡文能 第 3頁

Java String and Parser String in Java is not char array String is not

Java String and Parser String in Java is not char array String is not a char array in Java String is different from String. Buffer Elements in String/String. Buffer can be accessed via using the char. At( position ) method. The content of a String can not be modified substring ? capacity of a String. Buffer ? Size of a String Buffer ? - size <= capacity 交通大學資訊 程學系 蔡文能 第 4頁

Java String and Parser Characters In Java single characters are represented using the data

Java String and Parser Characters In Java single characters are represented using the data type char. ( do NOT confuse with the wrapper Character class) - char is one of the 8 primitive data types. - Character constants are written as symbols enclosed in single quotes, for example, 'a', 'X', and '5'. ( ' : apostrophe, " : quote ) To represent characters in computer, U. S. computer manufacturers devised several coding schemes. One coding scheme widely used today is ASCII (American Standard Code for Information Interchange). To accommodate the character symbols of non-English languages, the Unicode Consortium established the Unicode Worldwide Character Standard, commonly known as Unicode => http: //www. unicode. org/ 交通大學資訊 程學系 蔡文能 第 5頁

Java String and Parser Strings Not String Features: - Strings are objects and java.

Java String and Parser Strings Not String Features: - Strings are objects and java. lang. String is the class. Use 16 bit UNICODE All objects (java. lang. Object) have methods to. String(); Special treatment of the + operator "Object" + obj + "will call to. String( ) function" new String. Buffer("Object"). append(obj. to. String()). append("will call to. String( ) function"). to. String() Example: System. out. println("Hello World"); String hey = "Hello"; String you = "World"; System. out. println(hey + " " + you); int len = hey. length(); Notice the performance. 交通大學資訊 程學系 蔡文能 第 6頁

Java String and Parser String. Buffer For the String. Buffer Class - String. Buffer

Java String and Parser String. Buffer For the String. Buffer Class - String. Buffer provides length and char. At accessor methods, as well as the String class. - capacity method Returning the amount of space currently allocated for the String. Buffer, rather than the amount of space used. For example, in reverse. It method (next page) : - dest. capacity() will never change. - dest. length() will increase for each iteration. - Initializing a String. Buffer's capacity to a reasonable first guess. Minimizing the number of times memory must be allocated for it. 交通大學資訊 程學系 蔡文能 第 7頁

Java String and Parser String vs. String. Buffer Use the String class when you

Java String and Parser String vs. String. Buffer Use the String class when you are working with strings that cannot change. String. Buffer is used when you want to manipulate the contents of the string on the fly. public class Reverse. String { public static String reverse. It(String source) { int i, len = source. length(); String. Buffer dest = new String. Buffer(len); } } for (i = (len - 1); i >= 0; i--) dest. append(source. char. At(i)); return dest. to. String(); 交通大學資訊 程學系 蔡文能 第 8頁

Java String and Parser Creating Strings and String. Buffers Creating a String - String

Java String and Parser Creating Strings and String. Buffers Creating a String - String a = "Gobbledy gook. ”; - new String("Gobbledy gook. "); Creating a String. Buffer - String. Buffer dest = new String. Buffer(len); - String. Buffer's default constructor may leaves the buffer's length undetermined. - It's more efficient to specify the length of the buffer. 交通大學資訊 程學系 蔡文能 第 9頁

Java String and Parser String and String. Buffer are Objects String is a class

Java String and Parser String and String. Buffer are Objects String is a class in the java. lang package. Because String is a class, we need to create an instance of String in Java for string processing. Like any other objects, we need a declaration and object creation for the instances of the String class. For example, String name 1; name 1 = new String( "Latte" ); But we normally use a shorthand, instead, treating String objects much like primitive data. For example, These two statements are equivalent. String name 1; name 1 = "Latte"; 交通大學資訊 程學系 蔡文能 第 11頁

Java String and Parser Accessing char Elements in a String Individual characters in a

Java String and Parser Accessing char Elements in a String Individual characters in a String accessed with the char. At method. char. At(int index) - Returns the character at the specified index. - An index ranges from 0 to length( ) - 1. - The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing. 不可以直接使用 s[n] 而要改用 s. char. At(n) 交通大學資訊 程學系 蔡文能 第 12頁

Java String and Parser Accessing char Elements in a String (cont. ) String name

Java String and Parser Accessing char Elements in a String (cont. ) String name = "Example"; 0 1 2 3 4 5 6 E x a m p l e name This variable refers to the whole string. 交通大學資訊 程學系 蔡文能 name. char. At( 3 ) The method returns the character at position # 3. 第 13頁

Java String and Parser substring in a String/String. Buffer substring in a String accessed

Java String and Parser substring in a String/String. Buffer substring in a String accessed with the substring method. String substring(int begin. Index) - Returns a new string that is a substring of this string. The substring begins with the character at the specified begin. Index and extends to the end of this string. Examples: "unhappy". - substring(2) returns "happy" - substring(3) returns “appy" String substring(int begin. Index, int end. Index) - Returns a new string that is a substring of this string. The substring begins at the specified begin. Index and extends to the character at index end. Index - 1. Thus the length of the substring is end. Index-begin. Index. Examples: "hamburger". - substring(4, 8) returns "urge" "smiles". - substring(1, 5) returns "mile" 交通大學資訊 程學系 蔡文能 第 14頁

Java String and Parser Determining the String Size We determine the number of characters

Java String and Parser Determining the String Size We determine the number of characters in a String with the length method. String name = “Sumatra”, str 1 = “one”, str 2 = “”, str 3; name. length( ); 7 Error because no object is created for str 3, so it is a null. str 1. length( ); 3 str 2. length( ); 0 str 3. length( ); Error! 交通大學資訊 程學系 蔡文能 第 15頁

Java String and Parser Example using length( ) , char. At(int i) Reverse a

Java String and Parser Example using length( ) , char. At(int i) Reverse a string public class Reverse. String { public static String reverse. It(String source) { int i, len = source. length(); String. Buffer dest = new String. Buffer(len); } } for (i = (len - 1); i >= 0; i--) dest. append(source. char. At(i)); return dest. to. String(); 交通大學資訊 程學系 蔡文能 第 16頁

Java String and Parser More String/String. Buffer Methods int index. Of(int character) int last.

Java String and Parser More String/String. Buffer Methods int index. Of(int character) int last. Index. Of(int character) - Return the index of the first (last) occurrence of the specified character. int index. Of(int character, int from) int last. Index. Of(int character, int from) - Return the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index. void get. Chars(int src. Begin, int src. End, char[] dst, int dst. Begin) - Copies characters from this string into the destination character array. boolean equals(Object an. Object) - Compares this string to the specified object. Object clone() throws Clone. Not. Supported. Exception - Creates and returns a copy of this object. 交通大學資訊 程學系 蔡文能 第 17頁

Java String and Parser String Concatenation and the + Operator - In Java, you

Java String and Parser String Concatenation and the + Operator - In Java, you can use + to concatenate String: String cat = "cat"; System. out. println("con" + cat + "enation"); - But the compiler uses String. Buffer to implement concatenation behind the scenes. String cat = "cat"; System. out. println(new String. Buffer(). append("con"). append(cat). append("enation"). to. String()); 交通大學資訊 程學系 蔡文能 第 18頁

Java String and Parser Converting Objects to Strings The to. String Method public class

Java String and Parser Converting Objects to Strings The to. String Method public class Reverse. String { public static String reverse. It(String source) { int i, len = source. length(); String. Buffer dest = new String. Buffer(len); } } for (i = (len - 1); i >= 0; i--) dest. append(source. char. At(i)); return dest. to. String(); All classes inherit to. String from the Object class. - Many classes in the java. lang package override this method to provide an implementation that is meaningful to that class. The value. Of Method - You can use value. Of to convert variables of different types to String. System. out. println(String. value. Of(Math. PI)); 交通大學資訊 程學系 蔡文能 第 19頁

Java String and Parser Converting Strings to Numbers The "type wrapper" classes (Integer, Long,

Java String and Parser Converting Strings to Numbers The "type wrapper" classes (Integer, Long, Float, and Double) provide a class method named value. Of that converts a String to an object of that type. String pi. Str = "3. 14159"; Float pi = Float. value. Of(pi. Str); /*物件*/ float pi 2 = Float. parse. FLOAT(pi. Str); /*值*/ Object class method = static method 交通大學資訊 程學系 蔡文能 第 20頁

Java String and Parser TYPE Wrapper Long (1/2) As we mentioned before, every Primitive

Java String and Parser TYPE Wrapper Long (1/2) As we mentioned before, every Primitive data type has corresponding type wrapper. Long - Field Summary static long MAX_VALUE = The largest value of type long. static long MIN_VALUE = The smallest value of type long. static Class. TYPE = The Class object representing the primitive type long. - Constructor Summary Long(long value) : Constructs a newly allocated Long object that represents the primitive long argument. Long(String s) : Constructs a newly allocated Long object that represents the value represented by the string in decimal form. 交通大學資訊 程學系 蔡文能 第 21頁

Java String and Parser TYPE Wrapper Long (2/2) some methods of the class Long

Java String and Parser TYPE Wrapper Long (2/2) some methods of the class Long - static String to. Hex. String(long i) Creates a string representation of the long argument as an unsigned integer in base 16. - static String to. Octal. String(long i) Creates a string representation of the long argument as an unsigned integer in base 8. - static long parse. Long(String s) Parses the string argument as a signed decimal long. - static long parse. Long(String s, int radix) Parses the string argument as a signed long in the radix specified by the second argument. - static long value. Of(String s) Returns a new long object initialized to the value of the specified String. 交通大學資訊 程學系 蔡文能 第 22頁

Java String and Parser Strings and the Java Compiler Literal Strings - You can

Java String and Parser Strings and the Java Compiler Literal Strings - You can use literal strings anywhere you would use a String object. System. out. println("Hello World!"); - You can also use String methods directly from a literal string. int len = "Goodbye Cruel World". length(); - These two constructs are equivalent. String s = "Hala"; String s = new String("Hala"); But first one which is more efficient than the second. The second end up creating two String objects instead of one. 交通大學資訊 程學系 蔡文能 第 23頁

Java String and Parser More about I/O : C Read an Integer C static

Java String and Parser More about I/O : C Read an Integer C static char buf[999]; fgets(buf, sizeof(buf), stdin); /* read one line first */ static char buf[999]; file * fp; int haha; fp = fopen("myinput. dat", "rt"); fgets(buf, sizeof(buf), fp); /* read one line first */ haha = atol(buf); 交通大學資訊 程學系 蔡文能 第 24頁

Java String and Parser More about I/O : C++ Read an Integer C++ static

Java String and Parser More about I/O : C++ Read an Integer C++ static char buf[999]; cin. getline(buf, sizeof(buf) ); /* read one line first */ static char buf[999]; fstream fs; int haha; fs. open( "myinput. dat", ios: : in); fs. getline(buf, sizeof(buf) ); /* read one line first */ int haha = atol(buf); 交通大學資訊 程學系 蔡文能 第 25頁

Java String and Parser More about I/O : Java Read an Integer Java Use

Java String and Parser More about I/O : Java Read an Integer Java Use Buffered. Reader - Stream 要先轉為 Reader: Input. Stream. Reader - 把Reader 丟給Buffered. Reader 包起來 Use read. Line( ) in Buffered. Reader Use ? ? ? . parse? ? ? ( Double. parse. Double( your. String ) ); - i. e. , methods in class wrapper Use String. Tokenizer - To parse string contains several tokens 交通大學資訊 程學系 蔡文能 第 26頁

Java String and Parser Example: using Buffered. Reader Input. Stream. Reader isr = new

Java String and Parser Example: using Buffered. Reader Input. Stream. Reader isr = new Input. Stream. Reader(System. in); /* 鍵盤是以 byte 為單位的 Stream */ Buffered. Reader br = new Buffered. Reader(isr); /* Buffered. Reader 的 constructor 只接受 Reader */ /* 所以不能直接把 System. in 丟給它 */ String stmp = br. read. Line( ); /* 讀入一整列 */ long x = Long. parse. Long(stmp); /* if it is a long */ /* 使用 class wrapper */ double x = Double. parse. Double(stmp); /* if double */ 一列有多項輸入則可使用 String. Tokenizer 交通大學資訊 程學系 蔡文能 第 27頁

Java String and Parser Utilities ( java. util. * ) In java. util. *,

Java String and Parser Utilities ( java. util. * ) In java. util. *, - String. Tokenizer Vector Hashtable Properties. . . Vector is a growable array of objects. In Hashtable, an entry has two parts: a name and a value. - Pairs of name/value are objects. - Use hashing to find each pair. - Also known as associative array, or called “map”. In Properties, inherits from Hashtable. - Pairs of name/value are Strings. 交通大學資訊 程學系 蔡文能 第 28頁

Java String and Parser String. Tokenizer (1/3) 交通大學資訊 程學系 蔡文能 第 31頁

Java String and Parser String. Tokenizer (1/3) 交通大學資訊 程學系 蔡文能 第 31頁

Java String and Parser String. Tokenizer (2/3) import java. io. *; import java. util.

Java String and Parser String. Tokenizer (2/3) import java. io. *; import java. util. *; public class Test { Input. Stream. Reader isr= new Input. Stream. Reader(System. in); Buffered. Reader b = new Buffered. Reader(isr); public static void main ( String p[ ] ) throws Exception { new Test( ); } Test( ) throws Exception { System. out. print("In: "); String x = b. read. Line(); System. out. println("Got "+ x); String. Tokenizer s = new String. Tokenizer(x, " , t" ); while(s. has. More. Tokens( ) ){ System. out. println(s. next. Token( )); } System. out. println("======"); } } 交通大學資訊 程學系 蔡文能 第 32頁

Java String. Tokenizer (3/3)String and Parser System. out. print("rn. Your 三圍, 空白或逗號隔開: "); String

Java String. Tokenizer (3/3)String and Parser System. out. print("rn. Your 三圍, 空白或逗號隔開: "); String tmps = b. read. Line(); String. Tokenizer s = new String. Tokenizer(tmps, " , t"); int kk=0; round[2] = round[1] = round[0] =0; try{ while(s. has. More. Tokens () ) { round[ kk++ ] = Double. parse. Double( s. next. Token() ); if(kk > 3 ) break; } } catch (Exception e) { System. out. println("Missing "+ (4 -kk) + " round"); kk=3; } if(kk < 3 ) { System. out. println("Missing "+ (3 -kk) + " round"); } System. out. println("===Thank you!==="); Print. Stream myoo = System. out; myoo. println("rn=== Your Name is " + name); myoo. println("Height = " + height + " t" + "Weight = " + wet); myoo. print("Three circle(三圍)== "); Decimal. Format dd = new Decimal. Format("####0. 00"); myoo. print( dd. format( round[0] ) ); myoo. print( " , " + dd. format( round[1] ) +" , "+ dd. format(round[2]) ); myoo. println("rn======"); 交通大學資訊 程學系 蔡文能 第 33頁

Java String and Parser Vectors (1/5) This class is in the java. util package

Java String and Parser Vectors (1/5) This class is in the java. util package You make it available to your program with import statement “import java. util. Vector” or “import java. util. *” at the top of your program. Intended for dynamic sizes of elements. - Lets you add arbitrary objects to a list of objects - E. g. , add. Element(x); Reallocate the internal array when grows doubly (or a constant factor). 交通大學資訊 程學系 蔡文能 第 34頁

Java String and Parser Vectors (2/5) Performance: flexible and efficient - Access time complexity:

Java String and Parser Vectors (2/5) Performance: flexible and efficient - Access time complexity: O(1) - Time complexity for add. Element(x): Amortized for access: O(1) Times of calling malloc(): O((log n)/n) - Memory complexity: No more than 2 or constant times more. - But, Not efficient for remove. Element(). Not so efficient because it uses synchronized. - Sun internally uses a class named Fast. Vector, without synchronized. Similarly, for String. Buffer and Hashtable. - Note: for String, don’t concatenate strings in a loop! 交通大學資訊 程學系 蔡文能 第 35頁

Java String and Parser Vectors (3/5) 交通大學資訊 程學系 蔡文能 第 36頁

Java String and Parser Vectors (3/5) 交通大學資訊 程學系 蔡文能 第 36頁

Java 交通大學資訊 程學系 蔡文能 String and Parser Vectors (4/5) 第 37頁

Java 交通大學資訊 程學系 蔡文能 String and Parser Vectors (4/5) 第 37頁

Java String and Parser Vectors (5/5) java. util. Vector java. lang. Object | +

Java String and Parser Vectors (5/5) java. util. Vector java. lang. Object | + - - java. util. Abstract. Collection | + - - java. util. Abstract. List | + - - java. util. Vector Direct Known Subclasses: Stack 交通大學資訊 程學系 蔡文能 第 38頁

Java 交通大學資訊 程學系 蔡文能 Stack String and Parser 第 39頁

Java 交通大學資訊 程學系 蔡文能 Stack String and Parser 第 39頁

Java String and Parser javap java. util. Stack 交通大學資訊 程學系 蔡文能 第 40頁

Java String and Parser javap java. util. Stack 交通大學資訊 程學系 蔡文能 第 40頁

Java String and Parser java. util. Abstract. List 交通大學資訊 程學系 蔡文能 第 41頁

Java String and Parser java. util. Abstract. List 交通大學資訊 程學系 蔡文能 第 41頁

Java String and Parser java. util. Linked. List 交通大學資訊 程學系 蔡文能 第 42頁

Java String and Parser java. util. Linked. List 交通大學資訊 程學系 蔡文能 第 42頁

Java String and Parser Interface Queue java. util Interface Queue <E> Type Parameters: -

Java String and Parser Interface Queue java. util Interface Queue <E> Type Parameters: - E - the type of elements held in this collection Since: - JDK 1. 5 交通大學資訊 程學系 蔡文能 第 43頁

Java String and Parser Hashtable (1/3) Implements a hashtable in Java Hashtables have keys

Java String and Parser Hashtable (1/3) Implements a hashtable in Java Hashtables have keys and values Key “Joe” “Fred” “Heather” 交通大學資訊 程學系 蔡文能 Value employee object 第 44頁

Java String and Parser Hashtable (2/3) 交通大學資訊 程學系 蔡文能 第 45頁

Java String and Parser Hashtable (2/3) 交通大學資訊 程學系 蔡文能 第 45頁

Java String and Parser Hashtable (3/3) A hashtable can be used to quickly look

Java String and Parser Hashtable (3/3) A hashtable can be used to quickly look up an object associated with a key. The key uses the hashcode() method for fast access get() and put() are used to add and remove objects from the table elements() returns an object that lets you cycle through the hashtable Also take a look at Hash. Map (The Hash. Map class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. ) 交通大學資訊 程學系 蔡文能 第 46頁

Java String and Parser Properties 交通大學資訊 程學系 蔡文能 第 47頁

Java String and Parser Properties 交通大學資訊 程學系 蔡文能 第 47頁

Java String and Parser Properties The Properties class itself provides methods for the following:

Java String and Parser Properties The Properties class itself provides methods for the following: - Loading key/value pairs into a Property object from a stream Retrieving a value from its key Listing the keys and their values Enumerating over the keys Saving the properties to a stream Properties extends the Hashtable class: - Testing to see if a particular key or value is in the Properties object. Getting the current number of key/value pairs. Removing a key and its value. Adding a key/value pair to the Properties list. Enumerating over the values or the keys. Retrieving a value by its key. Finding out if the Properties object is empty. Important to be used as something like configuration files or *. ini files. 交通大學資訊 程學系 蔡文能 第 48頁

Java String and Parser The Life Cycle of Program's Properties 交通大學資訊 程學系 蔡文能 第

Java String and Parser The Life Cycle of Program's Properties 交通大學資訊 程學系 蔡文能 第 49頁

Java String and Parser Loading from File. Input. Stream Setting Up Your Properties Object

Java String and Parser Loading from File. Input. Stream Setting Up Your Properties Object - loading the default properties and loading the remembered properties: . . . // create and load default properties Properties default. Props = new Properties(); File. Input. Stream in = new File. Input. Stream("default. Properties"); default. Props. load(in); in. close(); // create program properties with default Properties application. Props = new Properties(default. Props); // now load properties from last invocation in = new File. Input. Stream("app. Properties"); application. Props. load(in); in. close(); 交通大學資訊 程學系 蔡文能. . . 第 50頁

Java String and Parser Saving to File. Output. Stream - The following example writes

Java String and Parser Saving to File. Output. Stream - The following example writes out the application properties from the previous example using Properties's save method. The default properties don't need to be saved each time because they never change. File. Output. Stream out = new File. Output. Stream("app. Properties"); application. Props. save(out, "---No Comment---"); out. close(); 交通大學資訊 程學系 蔡文能 第 51頁

Java String and Parser Properties Methods (1/2) - get. Property(String key, String default) Returns

Java String and Parser Properties Methods (1/2) - get. Property(String key, String default) Returns the value for the specified property. The second version allows you to provide a default value. If the key is not found, the default is returned. - list(Print. Stream s) - list(Print. Writer w) Writes all of the properties to the specified stream or writer. This is useful for debugging. - elements() - keys() - property. Names() Returns an Enumeration containing the keys or values (as indicated by the method name) contained in the Properties object. - size() Returns the current number of key/value pairs. 交通大學資訊 程學系 蔡文能 第 52頁

Java String and Parser Properties Methods (2/2) - contains(Object value) - contains. Key(Object key)

Java String and Parser Properties Methods (2/2) - contains(Object value) - contains. Key(Object key) Returns true if the value or the key is in the Properties object. Properties inherits these methods from Hashtable. Thus they accept Object arguments. You should pass in Strings. - put(Object key, Object value) Puts the key/value pair in the Properties object. - remove(Object key) Removes the key/value pair associated with key. Both put and remove come from Hashtable and thus take Objects. 交通大學資訊 程學系 蔡文能 第 53頁

Java String and Parser Properties File Format Each of the following lines specifies: -

Java String and Parser Properties File Format Each of the following lines specifies: - Key: "Truth"; Value: "Beauty". Truth = Beauty Truth: Beauty Truth : Beauty The following three lines specify a single property: fruits apple, banana, pear, cantaloupe, watermelon, kiwi, mango The empty string: cheese 交通大學資訊 程學系 蔡文能 第 54頁

Java String and Parser Using Properties to Manage Program Attributes An attribute has two

Java String and Parser Using Properties to Manage Program Attributes An attribute has two parts: a name and a value. For example - "os. name" is the name for one of the Java platform's system attributes. - Its value contains the name of the current operating system, such as “Linux". Many subsystems use properties files to set default properties. E. g. , - System Resource bundling Security manager Servlet JSP 交通大學資訊 程學系 蔡文能 第 55頁

Java String and Parser Introduction to Java Programming 謝謝捧場 http: //www. csie. nctu. edu.

Java String and Parser Introduction to Java Programming 謝謝捧場 http: //www. csie. nctu. edu. tw/~tsaiwn/oop/ 蔡文能 交通大學資訊 程學系 蔡文能 第 56頁