Java Reference
In-Depth Information
case equivalent, and otherwise, the method returns its original argument. Line 31 uses
Character
method
toLowerCase
to convert the character
c
to its lowercase equivalent.
The method returns the converted character if the character has a lowercase equivalent,
and otherwise, the method returns its original argument.
Figure 14.16 demonstrates static
Character
methods
digit
and
forDigit
, which
convert characters to digits and digits to characters, respectively, in different number sys-
tems. Common number systems include decimal (base 10), octal (base 8), hexadecimal
(base 16) and binary (base 2). The base of a number is also known as its
radix
. For more
information on conversions between number systems, see online Appendix J.
1
// Fig. 14.16: StaticCharMethods2.java
2
// Character class static conversion methods.
3
import
java.util.Scanner;
4
5
public
class
StaticCharMethods2
6
{
7
// executes application
8
public
static
void
main(String[] args)
9
{
10
Scanner scanner =
new
Scanner(System.in);
11
12
// get radix
13
System.out.println(
"Please enter a radix:"
);
14
int
radix = scanner.nextInt();
15
16
// get user choice
17
System.out.printf(
"Please choose one:%n1 -- %s%n2 -- %s%n"
,
18
"Convert digit to character"
,
"Convert character to digit"
);
19
int
choice = scanner.nextInt();
20
21
// process request
22
switch
(choice)
23
{
24
case
1
:
// convert digit to character
25
System.out.println(
"Enter a digit:"
);
26
int
digit = scanner.nextInt();
27
System.out.printf(
"Convert digit to character: %s%n"
,
28
Character.forDigit(digit, radix)
);
29
break
;
30
31
case
2
:
// convert character to digit
32
System.out.println(
"Enter a character:")
;
33
char
character = scanner.next().charAt(
0
);
34
System.out.printf(
"Convert character to digit: %s%n"
,
35
Character.digit(character, radix)
);
36
break
;
37
}
38
}
39
}
// end class StaticCharMethods2
Fig. 14.16
|
Character
class
static
conversion methods. (Part 1 of 2.)