Java Reference
In-Depth Information
Discussion
Nothing in the standard API formats Roman numerals. But the java.text.Format class is
designed to be subclassed for precisely such unanticipated purposes, so I have done just that
and developed a class to format numbers as Roman numerals. Here is a better and complete
example program of using it to format the current year. I can pass a number of arguments on
the command line, including a “ - ” where I want the year to appear (note that these arguments
are normally not quoted; the “ - ” must be an argument all by itself, just to keep the program
simple). I use it as follows:
$ java numbers.RomanYear Copyright (c) - Ian Darwin
Copyright (c) MMXIV Ian Darwin
$
The code for the RomanYear program is simple, yet it correctly puts spaces around the argu-
ments:
public
public class
class RomanYear
RomanYear {
public
public static
static void
void main ( String [] argv ) {
RomanNumberFormat rf = new
new RomanNumberFormat ();
Calendar cal = Calendar . getInstance ();
int
int year = cal . get ( Calendar . YEAR );
// If no arguments, just print the year.
iif ( argv . length == 0 ) {
System . out . println ( rf . format ( year ));
return
return ;
}
// Else a micro-formatter: replace "-" arg with year, else print.
for
for ( int
int i = 0 ; i < argv . length ; i ++) {
iif ( argv [ i ]. equals ( "-" ))
System . out . print ( rf . format ( year ));
else
System . out . print ( argv [ i ]);
// e.g., "Copyright"
System . out . print ( ' ' );
}
System . out . println ();
}
}
Search WWH ::




Custom Search