Java Reference
In-Depth Information
charObject.compareTo(new Character('d'))
returns
-2
charObject.equals(new Character('b'))
returns
true
charObject.equals(new Character('d'))
returns
false
java.lang.Character
+Character(value: char)
+charValue(): char
+compareTo(anotherCharacter: Character): int
+equals(anotherCharacter: Character): boolean
+isDigit(ch: char): boolean
+isLetter(ch: char): boolean
+isLetterOrDigit(ch: char): boolean
+isLowerCase(ch: char): boolean
+isUpperCase(ch: char): boolean
+toLowerCase(ch: char): char
Constructs a character object with
char
value.
Returns the
char
value from this object.
Compares this character with another.
Returns true if this character is equal to another.
Returns true if the specified character is a digit.
Returns true if the specified character is a letter.
Returns true if the character is a letter or a digit.
Returns true if the character is a lowercase letter.
Returns true if the character is an uppercase letter.
Returns the lowercase of the specified character.
+toUpperCase(ch: char): char
Returns the uppercase of the specified character.
F
IGURE
9.10
The
Character
class provides the methods for manipulating a character.
Most of the methods in the
Character
class are static methods. The
isDigit(char ch)
method returns
true
if the character is a digit, and the
isLetter(char ch)
method returns
true
if the character is a letter. The
isLetterOrDigit(char ch)
method returns
true
if
the character is a letter or a digit. The
isLowerCase(char ch)
method returns
true
if the
character is a lowercase letter, and the
isUpperCase(char ch)
method returns
true
if the
character is an uppercase letter. The
toLowerCase(char ch)
method returns the lowercase
letter for the character, and the
toUpperCase(char ch)
method returns the uppercase let-
ter for the character.
Now let's write a program that prompts the user to enter a string and counts the number of
occurrences of each letter in the string regardless of case.
Here are the steps to solve this problem:
1. Convert all the uppercase letters in the string to lowercase using the
toLowerCase
method in the
String
class.
2. Create an array, say
counts
of
26 int
values, each of which counts the occurrences of
a letter. That is,
counts[0]
counts the number of
a
s,
counts[1]
counts the number of
b
s, and so on.
3. For each character in the string, check whether it is a (lowercase) letter. If so, increment
the corresponding count in the array.
Listing 9.3 gives the complete program.
L
ISTING
9.3
CountEachLetter.java
1
import
java.util.Scanner;
2
3
public class
CountEachLetter {
4
/** Main method */
5
public static void
main(String[] args) {
6
// Create a Scanner
7 Scanner input =
new
Scanner(System.in);
8