Java Reference
In-Depth Information
Now here's the code for the
RomanNumberFormat
class. I did sneak in one additional class,
java.text.FieldPosition
. A
FieldPosition
simply represents the position of one nu-
meric field in a string that has been formatted using a variant of
NumberFormat.format()
.
You construct it to represent either the integer part or the fraction part (of course, Roman nu-
merals don't have fractional parts). The
FieldPosition
methods
getBeginIndex()
and
getEndIndex()
indicate where in the resulting string the given field wound up.
Example 5-4
is the class that implements Roman number formatting. As the comments indic-
ate, the one limitation is that the input number must be less than 4,000.
Example 5-4. RomanNumberFormat.java
public
public class
class
RomanNumberFormat
RomanNumberFormat
extends
extends
Format
{
private
private static
static final
final
long
long
serialVersionUID
= -
2303809319102357783L
;
/** Characters used in "Arabic to Roman", that is, format() methods. */
final
final static
static
char
char
A2R
[][] = {
{
0
,
'M'
},
{
0
,
'C'
,
'D'
,
'M'
},
{
0
,
'X'
,
'L'
,
'C'
},
{
0
,
'I'
,
'V'
,
'X'
},
};
static
static class
class
R2A
R2A
{
char
char
ch
;
public
public
R2A
(
char
char
ch
,
int
int
amount
) {
super
super
();
this
this
.
ch
=
ch
;
this
this
.
amount
=
amount
;
}
int
int
amount
;
}
final
final static
static
R2A
[]
R2A
= {
new
new
R2A
(
'M'
,
1000
),
new
new
R2A
(
'D'
,
500
),
new
new
R2A
(
'C'
,
100
),
new
new
R2A
(
'L'
,
50
),
new
new
R2A
(
'X'
,
10
),
new
new
R2A
(
'V'
,
5
),
new
new
R2A
(
'I'
,
1
),
};
/** Format a given double as a Roman Numeral; just truncate to a