Text Processing and Wrapper Classes II
- Contents
- Replacing a Substring in a
StringBuilderObject - Other
StringBuilderMethods - The
StringTokenizerClass - The
StringClasssplitMethod - Numeric Data Type Wrappers
- The
toStringMethods - Autoboxing and Unboxing
- Problem Solving Exercise
Replacing a Substring in a StringBuilder Object
The
StringBuilderclass has areplacemethod that replaces a specified substring with a string.The general form of a call to this method:
-
object.replace(start, end, str);
startspecifies the starting position of a substring in the caller, inclusive.endspecifies the ending position of the substring in the caller, exclusive.stris a string object.
-
After the method executes, the substring will be replaced with
str.Example code:
public class Program { public static void main(final String[] args) { final StringBuilder builder; // ......................... 012345678901234567890123456789012 builder = new StringBuilder("We moved from Chicago to Atlanta."); builder.replace(14, 21, "New York city"); System.out.println(builder); } }
Other StringBuilder Methods
The
StringBuilderclass also provides methods to set and delete characters in an object.Example code:
public class Program { public static void main(final String[] args) { // ............................................. 0123456789012345678901 final StringBuilder builder = new StringBuilder("I ate 100 blueberries!"); System.out.println(builder); builder.deleteCharAt(8); System.out.println(builder); builder.delete(9, 13); System.out.println(builder); builder.setCharAt(6, '5'); System.out.println(builder); } }
The StringTokenizer Class
The
StringTokenizerclass breaks a string down into its components, which are called tokens.Tokens are a series of words or other items of data separated by spaces or other characters.
- “peach raspberry strawberry vanilla”
- The string contains the following four tokens: peach, raspberry, strawberry, and vanilla.
The character that separates tokens is a delimiter.
- “17;43;23;46;6”
- This string contains tokens, 17, 43, 23, 46, and 6 that are delimited by semicolons.
Some programming problems require you to process a string that contains a list of items.
The process of breaking a string into tokens is knowns as tokenizing.
The Java API provides the
StringTokenizerclass that allows you to tokenize a string.The
StringTokenizerresides in thejava.utilpackage.import java.util.StringTokenizer;
StringTokenizerConstructorsCreate with default delimiters, whitespace characters
StringTokenizer(String str)
Create with a specified delimiter
StringTokenizer(String str, String delimiters)
Create with a specified delimiter and return the delimiter as tokens
StringTokenizer(String str, String delimiters, Boolean returnDelimeters)
StringTokenizerMethods-
myTokenizer.countTokens();
Counts the remaining tokens in the string.
-
hasMoreTokens- Tells whether or not there are more tokens to extract.
nextToken- Returns the next token in the string.
- Throws a
NoSuchElementExceptionif there are no more tokens in the string.
Book example:
Example code:
import java.util.StringTokenizer; public class Program { public static void main(final String[] args) { System.out.println("Constructor 1:"); StringTokenizer strTokenizer = new StringTokenizer("One Two Three"); while (strTokenizer.hasMoreTokens()) System.out.println(strTokenizer.nextToken()); System.out.println("Constructor 2:"); strTokenizer = new StringTokenizer("One Two Three", " "); while (strTokenizer.hasMoreTokens()) System.out.println(strTokenizer.nextToken()); System.out.println("Constructor 3:"); strTokenizer = new StringTokenizer("One Two Three", " ", false); while (strTokenizer.hasMoreTokens()) System.out.println(strTokenizer.nextToken()); } }Multiple Delimiters
The default delimiters for the
StringTokenizerclass are the whitespace characters.\n, \r, \t, \b, \f
Other multiple characters can be used as delimiters in the same string.
ycheng@hpu.edu- This string uses two delimiters: ‘@’ and ‘.’.
If non-whitespace is used as delimiters, the
trimmethod should be used on user input strings to avoid having whitespace become part of the last token.
Example code:
import java.util.StringTokenizer; public class Program { public static void main(final String[] args) { final StringTokenizer strTokenizer; strTokenizer = new StringTokenizer("ycheng@hpu.edu", "@."); while (strTokenizer.hasMoreTokens()) System.out.println(strTokenizer.nextToken()); } }
The String Class split Method
Tokenizes a
Stringobject and returns an array ofStringobjects.Each array element is one token.
Example code:
public class Program { public static void main(final String[] args) { final String str = "one two three four"; final String[] tokens = str.split(" "); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; System.out.println(token); } System.out.println("---------------------"); for (String token : tokens) System.out.println(token); } }
Numeric Data Type Wrappers
Java provides wrapper classes for all of the primitive data types.
The numeric primitive wrapper classes are:
To create objects from these wrapper classes, you can pass a value to the constructor:
Integer number = new Integer(7);
You can also assign a primitive value to a wrapper class object:
Integer number = 7; // may cause warning
The Parse Methods
Any string containing a number, such as 234.234, can be converted to a numeric data type.
Each of the numeric wrapper classes has a static method that converts a string to a number, e.g.,
- The
Integerclass has a method that converts aStringto anint - The
Doubleclass has a method that converts aStringto andouble
- The
These methods are known as parse methods because their names begin with the work “parse.”
The parse methods all throw a
NumberFormatExceptionif the string object does not represent a numeric value.
Example code:
public class Program { public static void main(final String[] args) { final byte myByte = Byte.parseByte("1"); final int myInt = Integer.parseInt("2599"); final short myShort = Short.parseShort("10"); final long myLong = Long.parseLong("15908"); final float myFloat = Float.parseFloat("12.3"); final double myDouble = Double.parseDouble("7945.6"); final String myString = String.format( "myByte: %d\n" + "myInt: %d\n" + "myShort: %d\n" + "myLong: %d\n" + "myFloat: %f\n" + "myDouble: %f", myByte, myInt, myShort, myLong, myFloat, myDouble); System.out.println(myString); } }
The toString Methods
Each of the numeric wrapper classes has a static
toStringmethod that converts a number to a string.This method accepts an argument and returns a string representation of that argument.
Example code:
public class Program { public static void main(final String[] args) { final int myInt = 12; final double myDouble = 14.95; System.out.println("myInt: " + Integer.toString(myInt)); System.out.println("myDouble: " + Double.toString(myDouble)); } }The
toBinaryString,toHexString, andtoOctalStringMethodsThe
IntegerandLongclasses have three additional methods:-
String toBinaryString(int num) String toHexString(int num) String toOctalString(int num)
Example code:
public class Program { public static void main(final String[] args) { final int number = 88; System.out.println(Integer.toString(number) + "D = " + Integer.toBinaryString(number) + "B"); System.out.println(Integer.toString(number) + "D = " + Integer.toHexString(number) + "H"); System.out.println(Integer.toString(number) + "D = " + Integer.toOctalString(number) + "O"); } }MIN_VALUEandMAX_VALUEThe numeric wrapper classes each have a set of static final variables:
MIN_VALUEMAX_VALUE
These variables hold the minimum and maximum values for a particular data type.
Example code:
public class Program { public static void main(final String[] args) { System.out.println("Minimum value for a byte: " + Byte.MIN_VALUE); System.out.println("Maximum value for a byte: " + Byte.MAX_VALUE); System.out.println("Minimum value for a short: " + Short.MIN_VALUE); System.out.println("Maximum value for a short: " + Short.MAX_VALUE); System.out.println("Minimum value for an int: " + Integer.MIN_VALUE); System.out.println("Maximum value for an int: " + Integer.MAX_VALUE); System.out.println("Minimum value for a long: " + Long.MIN_VALUE); System.out.println("Maximum value for a long: " + Long.MAX_VALUE); System.out.println("Minimum value for a float: " + Float.MIN_VALUE); System.out.println("Maximum value for a float: " + Float.MAX_VALUE); System.out.println("Minimum value for a double: " + Double.MIN_VALUE); System.out.println("Maximum value for a double: " + Double.MAX_VALUE); } }
Autoboxing and Unboxing
We can declare a wrapper class and assign a value:
Integer number = 7; // may cause warning
This is not an error because Java uses autoboxing to convert the primitive value to the boxed type.
Unboxing does the opposite with wrapper class variables.
// Autoboxes the int value 5. Integer myInt = 5; // may cause warning // Unboxing the Integer object myInt. int primitiveNumber = myInt; // may cause warning
We rarely need to declare numeric wrapper class objects, but they can be useful when we need to work with primitives in a context where primitives are not permitted.
Recall the
ArrayListclass, which works only with objects.-
ArrayList<int> list = new ArrayList<int>();
Error: “Syntax error on token ‘int’“
-
// Java 7: ArrayList<Integer> list = new ArrayList<>(); ArrayList<Integer> list = new ArrayList<Integer>();
Good
-
Example code:
import java.util.ArrayList; public class Program { public static void main(final String[] args) { // Java 7: final ArrayList<Integer> list = new ArrayList<>(); final ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); System.out.println(list); } }
Problem Solving Exercise
Consider the following problem.
Dr. Harrison keeps student scores in an Excel file. This can be exported as a comma separated text file.
Each student’s data will be on one line.
We want to write a Java program that will find a the average for each student.
The number of students changes each year.
Solution:
Example code:
import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; public class Program { public static void main(final String[] args) { final String fileName = "Grades.csv"; try { final FileReader reader = new FileReader(fileName); final Scanner scanner = new Scanner(reader); int index = 1; while (scanner.hasNextLine()) { final String line = scanner.nextLine(); final String[] tokens = line.split(","); float sum = 0; for (final String token : tokens) { try { sum += Float.parseFloat(token.trim()); } catch (NumberFormatException e) { System.err.println("Token '" + token + "' on '" + line + "' cannot be casted."); return; } } final float average = sum / tokens.length; System.out.println(String.format( "Average for student %d is %.2f", Integer.valueOf(index++), // Boxing example 1 new Float(average))); // Boxing example 2 } } catch (FileNotFoundException e) { System.err.println(fileName + " not found."); return; } } }