Java Reference
In-Depth Information
You can use the no-arg constructor in the
Date
class to create an instance for the cur-
rent date and time, the
getTime()
method to return the elapsed time since January 1, 1970,
GMT, and the
toString()
method to return the date and time as a string. For example, the
following code
java.util.Date date =
new
java.util.Date();
System.out.println(
"The elapsed time since Jan 1, 1970 is "
+
date.getTime() +
" milliseconds"
);
System.out.println(date.toString());
create object
get elapsed time
invoke
toString
displays the output like this:
The elapsed time since Jan 1, 1970 is 1324903419651 milliseconds
Mon Dec 26 07:43:39 EST 2011
The
Date
class has another constructor,
Date(long elapseTime)
, which can be used to
construct a
Date
object for a given time in milliseconds elapsed since January 1, 1970, GMT.
9.6.2 The
Random
Class
You have used
Math.random()
to obtain a random
double
value between
0.0
and
1.0
(excluding
1.0
). Another way to generate random numbers is to use the
java.util.Random
class, as shown in FigureĀ 9.11, which can generate a random
int
,
long
,
double
,
float
, and
boolean
value.
java.util.Random
+Random()
+Random(seed: long)
+nextInt(): int
+nextInt(n: int): int
+nextLong(): long
+nextDouble(): double
+nextFloat(): float
+nextBoolean(): boolean
Constructs a
Random
object with the current time as its seed.
Constructs a
Random
object with a specified seed.
Returns a random
int
value.
Returns a random
int
value between
0
and
n
(excluding
n
).
Returns a random
long
value.
Returns a random
double
value between
0.0
and
1.0
(excluding
1.0
).
Returns a random
float
value between
0.0F
and
1.0F
(excluding
1.0F
).
Returns a random
boolean
value.
F
IGURE
9.11
A
Random
object can be used to generate random values.
When you create a
Random
object, you have to specify a seed or use the default seed. A
seed is a number used to initialize a random number generator. The no-arg constructor cre-
ates a
Random
object using the current elapsed time as its seed. If two
Random
objects have
the same seed, they will generate identical sequences of numbers. For example, the following
code creates two
Random
objects with the same seed,
3
.
Random random1 =
new
Random(
3
);
System.out.print(
"From random1: "
);
for
(
int
i =
0
; i <
10
; i++)
System.out.print(random1.nextInt(
1000
) +
" "
);
Random random2 =
new
Random(
3
);
System.out.print(
"\nFrom random2: "
);
for
(
int
i =
0
; i <
10
; i++)
System.out.print(random2.nextInt(
1000
) +
" "
);
Search WWH ::
Custom Search