Java Reference
In-Depth Information
public
public class
class
FormatterDates
FormatterDates
{
public
public static
static
void
void
main
(
String
[]
args
) {
// Format number as dates e.g., 2014-06-28
System
.
out
.
printf
(
"%4d-%02d-%2d%n"
,
2014
,
6
,
28
);
// Format fields directly from a Date object: multiple fields from "1$"
// (hard-coded formatting for Date not advisable; see I18N chapter)
Date today
=
Calendar
.
getInstance
().
getTime
();
// Might print e.g., July 4, 2015:
System
.
out
.
printf
(
"Today is %1$tB %1$td, %1$tY%n"
,
today
);
}
}
Running this
FormatterDates
class produces the following output:
C:>
java io.FormatterDates
2014-06-28
Today is April 07, 2014
The astute reader will notice that this mechanism requires that the Java language now contain
a variable arguments mechanism. Variable argument lists have been the bane of developers
on many platforms and, indeed, they have finally come to Java. Briefly: the variable argu-
ment, which must be the last declaration in the method's header, is declared as
Type . . .
name
, and is treated as
Type[]
in the body of the method. The invocation must pass a
comma-separated list of arguments of the same or compatible types. See
lang/
VarArgsDemo.java
in the online source.
Scanning Input with StreamTokenizer
Problem
You need to scan a file with more fine-grained resolution than the
readLine( )
method of