Java Reference
In-Depth Information
exmpChoice.select("2");
}
return exmpChoice;
}
9.
Click the Exit button.
The choice has solved problem "D" because the user cannot enter an invalid value.
Formatting
Several very useful classes provide greater control over character and numeric data. The first one we will explore is
StringBuffer .
A string buffer acts just like a string but has more methods for content manipulation. For instance, the append
method allows you to easily concatenate strings, numbers, or constant text to a string buffer.
Another useful string buffer method is insert. The insert method allows the programmer to insert text anywhere
within the string buffer. The programmer must supply the insertion location within the string buffer, and you should
be aware that the beginning of the string buffer is position 0 not position 1.
The substring method lets you extract a range of characters (i.e., a substring) from within a string buffer.
With substring you must specify the starting and ending locations (separated by a comma) of the substring within
the string buffer.
Finally, the replace method lets you substitute characters within the string buffer. Again, you must specify the
range (i.e., location) of the characters to be replaced and the new text. Note that the number of new characters can be
smaller or larger than the number of characters being replaced.
Assuming the following:
StringBuffer a = new StringBuffer("abc");
String b = new String("def");
The following table shows these four methods with examples.
Method
Example
Result
a.append(b);
a.append(55);
a.append("xyz");
abcdef
abc55
abcxyz
.append
a.insert(0, b);
a.insert(1, 55);
a.insert(2, "xyz");
defabc
a55bc
abxyzc
.insert
a.substring(0, 1);
a.substring(0, 2);
a.substring(2, 3);
a
ab
c
.substring
a.replace(0, 2, b);
a.replace(1, 3, b);
a.replace(2, 3, "xyz");
defc
adef
abxyz
.replace
 
Search WWH ::




Custom Search