Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Counting Characters in Strings 115

The following things are taking place in the Wheelprogram:


. Lines 3–19: Phrases are stored in a string array called phrase.
. Line 20: An integer array called letterCountis created with 26 ele-
ments. This array is used to store the number of times each letter
appears. The order of the elements is from Ato Z. letterCount[0]
stores the count for letter A, letterCount[1]stores the count for B,
and so on, up to letterCount[25]for Z.
. Line 21: Aforloop cycles through the phrases stored in the phrase
array. The phrase.lengthvariable is used to end the loop after the
last phrase is reached.
. Line 22: Astring variable named currentis set with the value of the
current element of the phrasearray.
. Line 23: Acharacter array is created and stores all the characters in
the current phrase.
. Line 24: Aforloop cycles through the letters of the current phrase.
The letters.lengthvariable is used to end the loop after the last
letter is reached.
. Line 25: Acharacter variable called lettis created with the value of
the current letter. In addition to their text value, characters have a
numeric value. Because elements of an array are numbered, the
numeric value of each character is used to determine its element
number.
. Lines 26–28: An ifstatement weeds out all characters that are not
part of the alphabet, such as punctuation and spaces. An element of
theletterCountarray is increased by 1 depending on the numeric
value of the current character, which is stored in lett. The numeric
values of the alphabet range from 65 for ‘A’to 90 for ‘Z’. Because
the letterCountarray begins at 0 and ends at 25, ‘A’( 65 ) is sub-
tracted from lettto determine which array element to increase.
. Line 31: Aforloop cycles through the alphabet from ‘A’ to ‘Z’.
. Lines 32–34: The current letter is displayed followed by a semicolon
and the number of times the letter appeared in the phrases stored in
the phrasearray.


This project shows how two nested forloops can be used to cycle through
a group of phrases one letter at a time. Java attaches a numeric value to
each character; this value is easier to use than the character inside arrays.


NOTE
The numeric values associated
with each of the characters
from A to Z are those used by
the ASCII character set. The
ASCII character set is part of
Unicode,the full character set
supported by the Java lan-
guage. Unicode includes sup-
port for more than 60,000 dif-
ferent characters used in the
world’s written languages. ASCII
is limited to just 256.
Free download pdf