Java Reference
In-Depth Information
9
// Prompt the user to enter a string
10 System.out.print(
"Enter a string: "
);
11 String s = input.nextLine();
12
13
input string
// Invoke the countLetters method to count each letter
countLetters(s.toLowerCase())
14
int
[] counts =
;
count letters
15
16
// Display results
17
for
(
int
i =
0
; i < counts.length; i++) {
18
if
(counts[i] !=
0
)
19 System.out.println((
char
)(
'a'
+ i) +
" appears "
+
20 counts[i] + ((counts[i] ==
1
) ?
" time"
:
" times"
));
21 }
22 }
23
24
/** Count each letter in the string */
25
public static int
[] countLetters(
String s
) {
26
int
[] counts =
new int
[
26
];
27
28
s.length()
for
(
int
i =
0
; i <
; i++) {
29
if
(
Character.isLetter(s.charAt(i))
)
count a letter
30 counts[s.charAt(i) -
'a'
]++;
31 }
32
33
return
counts;
34 }
35 }
abababx
Enter a string:
a appears 3 times
b appears 3 times
x appears 1 time
The main method reads a line (line 11) and counts the number of occurrences of each letter in
the string by invoking the
countLetters
method (line 14). Since the case of the letters is
ignored, the program uses the
toLowerCase
method to convert the string into all lowercase
and pass the new string to the
countLetters
method.
The
countLetters
method (lines 25-34) returns an array of
26
elements. Each element
counts the number of occurrences of a letter in the string
s
. The method processes each char-
acter in the string. If the character is a letter, its corresponding count is increased by
1
. For
example, if the character (
s.charAr(i)
) is
a
, the corresponding count is
counts['a' -
'a']
(i.e.,
counts[0]
). If the character is
b
, the corresponding count is
counts['b' -
'a']
(i.e.,
counts[1]
), since the Unicode of
b
is
1
more than that of
a
. If the character is
z
,
the corresponding count is
counts['z' - 'a']
(i.e.,
counts[25]
), since the Unicode of
z
is
25
more than that of
a
.
9.12
✓
✓
How do you determine whether a character is in lowercase or uppercase?
Check
9.13
How do you determine whether a character is alphanumeric?
Point
9.14
Show the output of the following code.
public class
Test {
public static void
main(String[] args) {
String s =
"Hi, Good Morning"
;
System.out.println(m(s));
}