Java Reference
In-Depth Information
exceptions are, and how you should deal with them, in Chapter 7. For the moment, just note that the specific
type of exception thrown in this case is called IndexOutOfBoundsException . Its name is rather a mouthful,
but quite explanatory.
To avoid unnecessary errors of this kind, you obviously need to be able to determine the length of a
String object. To obtain the length of a string, you just need to call its length() method. Note the differ-
ence between this and the way you got the length of an array. Here you are calling a method, length() , for
a String object, whereas with an array you were accessing a data member, length . You can explore the use
of the charAt() and length() methods in the String class with another example.
TRY IT OUT: Getting at Characters in a String
In the following code, the soliloquy is analyzed character-by-character to determine the vowels, spaces,
and letters that appear in it:
public class StringCharacters {
public static void main(String[] args) {
// Text string to be analyzed
String text = "To be or not to be, that is the question;"
+"Whether 'tis nobler in the mind to suffer"
+" the slings and arrows of outrageous fortune,"
+" or to take arms against a sea of troubles,"
+" and by opposing end them?";
int spaces = 0,
// Count of
spaces
vowels = 0,
// Count of
vowels
letters = 0;
// Count of
letters
// Analyze all the characters in the string
int textLength = text.length();
// Get string
length
for(int i = 0; i < textLength; ++i) {
// Check for vowels
char ch = Character.toLowerCase(text.charAt(i));
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u') {
vowels++;
}
//Check for letters
if(Character.isLetter(ch)) {
letters++;
}
// Check for spaces
Search WWH ::




Custom Search