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

(singke) #1
ptg7068951

Counting Characters in Strings 113

14: for (int i = 0; i < names.length; i++) {
15: System.out.print(i + “: “+ names[i] + “ “);
16: }
17: System.out.println();
18: }
19: }


When you run this Java program, it displays a list of 13 names in their orig-
inal order, sorts the names, and then redisplays the list. Here’s the output:


Output▼


The original order:
0: Lauren 1: Audrina 2: Heidi 3: Whitney 4: Stephanie 5: Spencer
6: Lisa 7: Brody 8: Frankie 9: Holly 10: Jordan 11: Brian
12: Jason
The new order:
0: Audrina 1: Brian 2: Brody 3: Frankie 4: Heidi 5: Holly
6: Jason 7: Jordan 8: Lauren 9: Lisa 10: Spencer 11: Stephanie 12:
Whitney


When you’re working with strings and the basic types of variables such as
integers and floating-point numbers, you only can sort them by ascending
order using the Arraysclass. You can write code to do your own sorts by
hand if you desire a different arrangement of elements during a sort, or
you want better efficiency than the Arraysclass provides.


Counting Characters in Strings


The letters that appear most often in English are E, R, S, T, L, N, C, D, M,
and O, in that order. This is a fact worth knowing if you ever find yourself
on the syndicated game show Wheel of Fortune.


The next program you create this hour counts letter frequency in as many
different phrases and expressions as you care to type. An array is used to
count the number of times that each letter appears. When you’re done, the
program presents the number of times each letter appeared in the phrases.


Create a new Empty Java File in NetBeans called Wheel.java, fill it with
the contents of Listing 9.3 and save the file when you’re finished. Feel free
to add additional phrases between Lines 17 and 18, formatting them exact-
ly like Line 17.


NOTE
If you’re unfamiliar with the
show,Wheel of Fortuneis a
game in which three contest-
ants guess the letters of a
phrase,name,or quote. If they
get a letter right and it’s a con-
sonant,they win the amount of
money spun on a big wheel. To
re-create the experience,play
hangman with your friends in
front of a studio audience,hand
out random amounts of money
when someone guesses a letter
correctly,and give the winner a
new Amana stove.

LISTING 9.2 Continued

Free download pdf