Java Reference
In-Depth Information
How It Works
We use one random number generator here that we create using the default constructor, so it will be
seeded with the current time and will produce a different sequence of values each time the program is
run. We simulate throwing the dice in the
for
loop. For each throw we need a random number
between 1 and 6 for each die. The easiest way to produce this is to add one to the value returned by the
nextInt()
method when we pass 6 as the argument. If we wanted to make a meal of it we could
obtain the same result by using the statement:
die1 = 1 + abs(diceValues.nextInt())%6; // Number from 1 to 6
Remember that the pseudo-random integer values that we get from the
nextInt()
method will be
uniformly distributed across the whole range of possible values for type
int
, positive and negative. That's
why we need to use the
abs()
method from the
Math
class here to make sure we end up with a positive die
value. The remainder after dividing the value resulting from
abs(diceValues.nextInt())
by 6 will be
between 0 and 5. Adding 1 to this produces the result we want.
Remember that the odds against a double six are 36:1, so you'll only succeed once on average out of
every six times you run the example.
Now we'll move on to look at dates and times.
Dates and Times
There are quite a few classes in the
java.util
package that are involved with dates and times,
including the
Date
class, the
Calendar
class, and the
GregorianCalendar
class. In spite of the
class name, a
Date
class object actually defines a particular instant in time to the nearest millisecond,
measured from January 1, 1970, 00:00:00 GMT. Since it is relative to a particular instant in time, it also
corresponds to a date. The
Calendar
class is the base class for
GregorianCalendar
, which
represents the sort of day/month/year calendar everybody is used to, and also provides methods for
obtaining day, month, and year information from a
Date
object. A
Calendar
object is always set to a
particular date - a particular instant on a particular date to be precise- but you can change it by various
means. From this standpoint a
GregorianCalendar
object is more like one of those desk calendars
that just show one date, and you can flip over the days, months, or years to show another date.
There is also the
TimeZone
class that defines a time zone that can be used in conjunction with a
calendar, and that you can use to specify the rules for clock changes due to daylight saving time. The
ramifications of handling dates and times are immense so we will only be able to dabble here, but at
least you will get the basic ideas. Let's take a look at
Date
objects first.