Presentation is loading. Please wait.

Presentation is loading. Please wait.

Text Processing and More about Wrapper Classes

Similar presentations


Presentation on theme: "Text Processing and More about Wrapper Classes"— Presentation transcript:

1 Text Processing and More about Wrapper Classes
Chapter 10 Text Processing and More about Wrapper Classes

2 Contents Introduction to Wrapper Classes
Character Testing and Conversion with the Character Class More String Methods The StringBuilder Class Tokenizing Strings Wrapper Classes for the Numeric Data Types Focus on Problem Solving

3 I. Introduction to Wrapper Classes
Java provides wrapper classes for the primitive data types. A wrapper class is a class that is “wrapped around” a primitive data type and allows us to create objects instead of variables. The wrapper class for a given primitive data type contains not only a value of that type, but also methods that perform operations related to the type.

4 I. Introduction to Wrapper Classes
Although these wrapper classes can be used to created objects instead of variables, few programmers use them that way. One reason is because the wrapper classes are immutable (we can not change the object's value). Another reason is because they are not as easy to use as variables for simple operations.

5 II. Character Testing and Conversion with the Character Class
The Character class is a wrapper class for the char data type. It is provide numerous methods for testing and converting character data. Some static methods for testing char values boolean isDigit(char ch) boolean isLetter(char ch) boolean isLetterOrDigit(char ch) boolean isLowerCase(char ch) boolean isUpperCase(char ch) boolean isSpaceChar(char ch) boolean isWhiteSpaceChar(char ch)

6 II. Character Testing and Conversion with the Character Class
Some static methods for case conversion char toLowerCase(char ch) char toUpperCase(char ch) If the argument is already uppercase, the toUpperCase method returns it unchanged. Any non-letter argument (for example: *, $, &, % ) passed to toLowerCase and toUpperCase is returned as it is.

7

8 The Customer Number Problem

9 The Customer Number Problem

10 The Circle Area Problem

11 The Circle Area Problem

12 Checkpoint 10.1 10.2 10.3 10.4 10.5 10.6

13 III. More String Methods
The String class provides several methods for searching and working with String objects. Searching for substrings The term substring commonly is used to refer to a string that is part of another string. boolean startsWith(String str) boolean endsWith(String str) boolean regionMatches(int start, String str, int start2, int n) boolean regionMatches(boolean ignoreCase, int start, String str, int start2, int n)

14 III. More String Methods
String str = “Four score and seven years ago”; if(str.startsWith(“Four”)) System.out.println(“The string starts with Four.”); else System.out.println(“The string does not start with Four.”); String str = “Four score and seven years ago”; if(str.endsWith(“ago”)) System.out.println(“The string ends with Four.”); else System.out.println(“The string does not end with Four.”);

15 The Person Search Problem

16 III. More String Methods
String str = “Four score and seven years ago”; String str2 = “Those seven years passed quickly”; if(str.regionMatches(15, str2, 6, 11)) System.out.println(“The regions match.”); else System.out.println(“The regions do not match.”); String str = “Four score and seven years ago”; String str2 = “THOSE SEVEN YEARS PASSED QUICKLY.”; if(str.regionMatches(15, str2, 6, 11)) System.out.println(“The regions match.”); else System.out.println(“The regions do not match.”);

17 III. More String Methods
String methods for getting a character or substring's location: int indexOf(char ch) int indexOf(char ch, int start) int indexOf(String str) int indexOf(String str, int start) int lastIndexOf(char ch) int lastIndexOf(char ch, int start) int lastIndexOf(String str) int lastIndexOf(String str, int start)

18 III. More String Methods
String str = “Four score and seven years ago”; int first, last; first = str.indexOf('r'); last = str.lastIndexOf('r'); System.out.println(“The letter r first appears at “ “position “ + first; System.out.println(“The letter r last appears at “ “position “ + last; The letter r first appears at position 3. The letter r last appears at position 24.

19 III. More String Methods
String str = “Four score and seven years ago”; int position; System.out.println(“The letter r appears at the “ “following locations:”); position = str.indexOf('r'); while(position != -1) { System.out.println(“position); position = str.indexOf('r', position + 1); } The letter r appears at the following locations:

20 III. More String Methods
String str = “Four score and seven years ago”; int position; System.out.println(“The letter r appears at the “ “following locations:”); position = str.lastIndexOf('r'); while(position != -1) { System.out.println(“position); position = str.lastIndexOf('r', position - 1); } The letter r appears at the following locations:

21 III. More String Methods
String str = “and a one and a two and a three”; int position; System.out.println(“The word and appears at the “ “following locations:”); position = str.indexOf(“and”); while(position != -1) { System.out.println(“position); position = str.indexOf(“and”, position + 1); } The word and appears at the following locations:

22 III. More String Methods
String str = “and a one and a two and a three”; int position; System.out.println(“The word and appears at the “ “following locations:”); position = str.lastIndexOf(“and”); while(position != -1) { System.out.println(“position); position = str.lastIndexOf(“and”, position - 1); } The word and appears at the following locations:

23 III. More String Methods
Extracting Substring String substring(int start) String substring(int start, int end) void getChars(int start, int end, char[] array, int arrayStart) char[] toCharArray()

24 III. More String Methods
String fullName = “Cynthia Susan Lee”; String lastName = fullName.substring(14); System.out.println(“The full name is “ + fullName; System.out.println(“The last name is “ + lastName; The full name is Cynthia Susan Lee The last name is Lee

25 III. More String Methods
String fullName = “Cynthia Susan Lee”; String middleName = fullName.substring(8, 13); System.out.println(“The full name is “ + fullName); System.out.println(“The middle name is “ + middleName); The full name is Cynthia Susan Lee The middle name is Susan

26 III. More String Methods
String fullName = “Cynthia Susan Lee”; char[] nameArray = new char[5]; fullName.getChars(8, 13, nameArray, 0); System.out.println(“The full name is “ + fullName); System.out.println(“The values in the array are:”); for(int i = 0; i<nameArray.length; i++) System.out.print(nameArray[i] + “ “); The full name is Cynthia Susan Lee The values in the array are: S u s a n

27 III. More String Methods
String fullName = “Cynthia Susan Lee”; char[] nameArray; arrayName = fullName.toCharArray(); System.out.println(“The full name is “ + fullName); System.out.println(“The values in the array are:”); for(int i = 0; i<nameArray.length; i++) System.out.print(nameArray[i] + “ “); The full name is Cynthia Susan Lee The values in the array are: C y n t h I a S u s a n L e e

28 The String Analyzer Problem

29 The String Analyzer Problem

30 III. More String Methods
Methods that returns a modified String String concate(String str) String replace(char oldChar, char newChar) String strim()

31 III. More String Methods
String fullName; String firstName = “Timothy ”; String lastName = “Haynes”; fullName = firstName + lastName; String fullName; String firstName = “Timothy ”; String lastName = “Haynes”; fullName = firstName.concate(lastName);

32 III. More String Methods
String str1 = “Tom Talbert Tried Trains”; String str2; str2 = str1.replace('T', 'D'); System.out.println(str1); System.out.println(str2); Tom Talbert Tried Trains Dom Dalbert Dried Drains

33 III. More String Methods
String greeting1 = “ Hello “; String greeting2; greeting2 = greeting1.trim(); System.out.println(“*” + greeting1 + “*”); System.out.println(“*” + greeting2 + “*”); * Hello * Hello

34 III. More String Methods
The static valueOf methods String valueOf(boolean b) String valueOf(char c) String valueOf(char[] array) String valueOf(char[] array, int subscript, int cout) String valueOf(double number) String valueOf(float number) String valueOf(int number) String valueOf(long number)

35 III. More String Methods
boolean b = true; char[] letters = {'a', 'b', 'c', 'd', 'e'}; double d = ; int i = 7; System.out.println(String.valueOf(b)); System.out.println(String.valueOf(letters)); System.out.println(String.valueOf(letters, 1, 3)); System.out.println(String.valueOf(d)); System.out.println(String.valueOf(i)); true abcde bcd 7

36 Checkpoint 10.7 10.8 10.9 10.10 10.11 10.12 10.13 10.14 10.15 10.16

37 IV. The StringBuilder Class
The StringBuilder class is similar to the String class, except that we may change the contents of StringBuilder objects. The StringBuilder class provides several useful methods that the String class does not have. The StringBuilder class have methods that allows us to modify the contents of objects without creating a new object in memory. The StringBuilder object will grow or shrink in size, as needed, to accommodate the changes.

38 IV. The StringBuilder Class
StringBuilder constructors StringBuilder(): It gives the object enough storage space to hold 16 characters, but no characters are stored in it. StringBuilder(int length): It gives the object enough space to hold length characters, but no characters are stored in it. StringBuilder(String str): It initializes the object with the string in str. The object's initial storage space will be the length of the string plus 16.

39 IV. The StringBuilder Class
One limitation of the StringBuilder class is that we cannot use the assignment operator to assign strings to StringBuilder objects. StringBuilder city = “Charleston”; StringBuilder city = new StringBuilder(“Charleston”);

40 IV. The StringBuilder Class
The StringBuilder class provides many of the same methods as the String class. char charAt(int position) int getChars(int start, int end, char[] array, int arrayStart) int indexOf(String str) int indexOf(String str, int start) int lastIndexOf(String str) int lastIndexOf(String str, int start) int length() String substring(int start) String substring(int start, int end)

41 IV. The StringBuilder Class
In addition, the StringBuilder class provides several methods that the String class does not have. The append methods The general format: object.append(item); These methods append a string representation of their argument to the calling object's current contents.

42 The append methods StringBuilder str = new StringBuilder(); //Append values to the object str.append(“We sold “); str.append(12); str.append(“ doughnuts for $”); str.append(15.95); System.out.println(str); We sold 12 doughnuts for 15.95

43 IV. The StringBuilder Class
The insert Methods The general format: object.append(start, item); start is the starting position of the insertion and item is the item to be inserted. These methods insert a value into the calling objects's string.

44 The insert Methods StringBuilder str = new StringBuilder(“July sold cars.”); char[] array = { 'w', 'e', ' ' }; //Insert values to the object str.insert(0, “In “); str.insert(8, array); str.insert(16, 20); str.insert(18, ' '); System.out.println(str); In July we sold 20 cars.

45 The insert Methods Problem: Convert an unformatted telephone number, such as , to a formatted telephone number, such as (919)

46 IV. The StringBuilder Class
The replace Method object.replace(start, end, str); It replaces a specified substring (from start to end) with a string (str). StringBuilder str = new StringBuilder(“We moved from Chicago to Atlanta.”); str.replace(14, 21, “New York”); System.out.println(str); We moved from New York to Atlanta.

47 IV. The StringBuilder Class
StringBuilder delete(int start, int end) StringBuilder deleteCharAt(int position) void setCharAt(int position, char ch)

48 IV. The StringBuilder Class
StringBuilder str = new StringBuilder(“I ate blueberries!”); System.out.println(str); //Delete the '0' str.deleteCharAt(8); //Delete “blue” str.delete(9, 13); System.out.println(str); //Change the '1' to '5' str.setCharAt(6, '5'); System.out.println(str); I ate 100 blueberries. I ate 10 berries. I ate 50 berries.

49 Checkpoint 10.17 10.18 10.19 10.20 10.21 10.22 10.23 10.24

50 V. Tokenizing Strings Tokenizing a string is a process of breaking a string down into its components, which are called tokens. Sometime a string will contain a series of words or other items of data separated by spaces or other characters. “peach raspberry strawberry vanilla” contains four items of data, peach, raspberry, strawberry, vanilla. Space is used as a delimiter. In programming terms, items such as these are known as tokens.

51 V. Tokenizing Strings “17;92;81;12;46;5” contains the following tokens: 17, 92, 81, 12, 46, and 5. The semicolon is used as a delimiter. “ ” contains the following tokens: 3, 22, and The delimiter is the hyphen character. “home/rsullivan/data” contains the tokens: home, rsullivan, data, and the delimiter is the / character.

52 The StringTokenizer Class
The StringTokenizer constructors StringTokenizer(String str): The string to be tokenized is passed into str. Whitespace characters (space, tab, and newline) are used as delimiters. StringTokenizer(String str, String delimiters): The string to be tokenized is passed into str. The characters in delimiters will be used as delimiters. StringTokenizer(String str, String delimiters, boolean returnDelimiters): The string to be tokenized is passed into str. The characters in delimiters will be used as delimiters. If the returnDelimiters is true, the delimiters will be included as tokens.

53 The StringTokenizer Class
StringTokenizer strTokenizer = new StringTokenizer(“ ”); StringTokenizer strTokenizer = new StringTokenizer(“ ”, “-”); StringTokenizer strTokenizer = new StringTokenizer(“ ”,”-”, true);

54 The StringTokenizer Class
Extracting Tokens int countTokens(): returns the number of tokens left in the string boolean hasMoreTokens(): returns true if there are tokens left in the string. Otherwise it returns false. String nextToken(): returns the next token found in the string.

55 Extracting Tokens StringTokenizer strTokenizer = new StringTokenizer(“One Two Three”); while(strTokenizer.hasMoreTokens()) { System.out.println(strTokenizer.nextToken()); } One Two Three

56 Extracting Tokens Problem: Extracting the month, day, and year from a string containing a date.

57

58

59

60 The StringTokenizer Class
Using Multiple Delimiters StringTokenizer strTokenizer = new while(strTokenizer.hasMoreTokens()) { System.out.println(strTokenizer.nextToken()); } joe gaddisbooks com

61 The StringTokenizer Class
Trimming a String before Tokenizing When we are tokenizing a string that was entered by the user, the string may contains leading or trailing whitespace characters, they will become part of the tokens. String str = “ one;two;three ”; StringTokenizer strTokenizer = new StringTokenizer(str, “;”); while(strTokenizer.hasMoreTokens()) { System.out.println(“*”+strTokenizer.nextToken()+“*”); } * one* *two* *three *

62 Trimming a String before Tokenizing
String str = “ one;two;three ”; StringTokenizer strTokenizer = new StringTokenizer(str.trim(), “;”); while(strTokenizer.hasMoreTokens()) { System.out.println(“*”+strTokenizer.nextToken()+“*”); } *one* *two* *three*

63 The String Class's split Method
The split method of the String class The split method tokenizes a string and returns an array of String object. Each element in the array is one of the token. String str = "one two three four"; // Get the tokens, using a space delimiter. String[] tokens = str.split(" "); // Display the tokens. for (String s : tokens) System.out.println(s); one two three four

64 The String Class's split Method
String str = "one and two and three and four"; //Get the tokens, using “ and “ as the delimiter. String[] tokens = str.split(" and "); // Display the tokens. for (String s : tokens) System.out.println(s); one two three four

65 The String Class's split Method
String str = //Get the tokens, and . as delimiters. String[] tokens = // Display the tokens. for (String s : tokens) System.out.println(s); Joe gaddisbooks com

66 Checkpoint 10.25 10.26 10.27 10.28

67 VI. Wrapper Classes for the Numeric Data Types
Java API provides wrapper classes for each of the numeric data types. Wrapper Class Primitive Type It Applies To Byte byte Double double Float float Integer int Long long Short short

68 VI. Wrapper Classes for the Numeric Data Types
The Static toString Methods Each of the numeric wrapper classes has a static toString method that converts a number to a string. int i = 123; double d = 14.95; String str1 = Integer.toString(i); String str2 = Double.toString(d);

69 VI. Wrapper Classes for the Numeric Data Types
The toBinaryString, toHexString, toOctalString Methods of the Integer and Long Wrapper classes: Accept an integer as an argument and return a string representation of that number converted to binary, hexadecimal, or octal. int number = 14; System.out.println(Integer.toBinaryString(number)); System.out.println(Integer.toHexString(number)); System.out.println(Integer.toOctalString(number)); 1110 e 16

70 VI. Wrapper Classes for the Numeric Data Types
The MIN_VALUE and MAX_VALUE Constants Each of the numeric wrapper classes has a set of static final variables named MIN_VALUE and MAX_VALUE. The MIN_VALUE variable holds the minimum value for that type. The MAX_VALUE variable holds the maximum value for that type. System.out.println(“”The minimum value for an int is “ + Integer.MIN_VALUE); System.out.println(“”The maximum value for an int is “ + Integer.MAX_VALUE);

71 VI. Wrapper Classes for the Numeric Data Types
Autoboxing and Unboxing Autoboxing is Java's process of automatically boxing up a value inside an object. Integer number = new Integer(7); Integer number; number = 7; //Autoboxing

72 Autoboxing and Unboxing
Unboxing is the opposite of boxing. It is the process of converting a wrapper class object to a primitive type. Integer myInt = 5; //Autoboxing the value 5 int primitiveNumber; primitiveNumber = myInt; //Unboxing the object

73 Autoboxing and Unboxing
ArrayList<int> list = new ArrayList<int>(); //ERROR ArrayList<Integer> list = new ArrayList<Integer>(); //Okay To store an int value in the the ArrayList: ArrayList<Integer> list = new ArrayList<Integer>(); Integer myInt = 5; list.add(myInt); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); //Autoboxing To retrieve a value from the ArrayList: ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); //Autoboxing int primitiveNumber = list.get(0); //Unboxing

74 Checkpoint 10.29 10.30 10.31

75 VII. Focus on Problem Solving
The TestScoreReader Class Professor Harrison keeps her students' test scores in a Microsoft Excel spreadsheet. Each column holds a test score and each row represents the scores for one student.

76 The TestScoreReader Class
The data in a spreadsheet is exported, each row is written to a line, and the values in the cells are separated by commas. It will be written to a text file in the following format (comma separate value file format (.csv)) Dr. Harrison writes a Java program to read test scores from a csv file and show the average of each line of scores.

77 The TestScoreReader Class
The UML Class Diagram

78 VII. Focus on Problem Solving

79

80


Download ppt "Text Processing and More about Wrapper Classes"

Similar presentations


Ads by Google