Professor: If I used round() , then yes, I would get 5 5 possible different values. But
I used floor() because it is more fair. The problem with rounding is that it rounds
the value to its n earest integer, so on ly numbers from zero to approximately 0.49999
are rounded to zero. This is only half as much as there are values rounded to, say, one.
Every value from 0.5 to approximately 1.49999 is rounded to one, which makes the
probability of getting one twice of that of getting zero. On the other hand, floor()
rounds values down to the nearest integer, so all nu mbers get equally sized ranges.
Note that, because random() n ever returns one, the largest possible value returned by
the expression Math.rand om()*54 is in fact less than 54, which means that floor()
in our progra m can never return 54.
Maria: Shouldn’t the drawn numbers in our lottery all be d ifferent? I suspect that our
solution does not guarantee that.
Professor: Exactly. And that’s the trouble with this solution. There is absolutely no
memory of the numbers that have already been drawn, and it can easily h appen that a
number is drawn two or even more times.2
8.4 do/while Loop
Professor: One strategy of securing that two random numbers are different is to draw
them again if they a re equal. If they’re still equal, then draw them again. And again.
Eventually, they ought to turn out different. You probably guessed that we need a loop
for that, and you might have noticed that the first drawing should be perf ormed before
we test for equality. There’s a slight inconvenience with the while loop in that its
body is executed after the loop condition is checked. While the problem is not fatal,
it is still more comf ortable to use the do/while loop for our particular problem. The
do/while loop is very much like the while loop, with one fundamental difference:
the loop condition is tested at the end of the loop, which means that the loop body is
executed at least once. This is the syntax of th e do/while loop:
do
statement
while (expression );
This loop isn’t used as often as its while co unterpart but you will find it occasionally
in existing code , and you may even want to use it for yourselves, as we’re going to do
now.
Maria: Why have you put a semico lon at the end of the do/while statement? Other
control statements don’t have it.
Professor: Most statements terminate with a semicolon but there are exceptions. A
compound statement and switch, for example, do not require a semicolon at the en d.
Now, if you want to draw two different numbers, this is the code that does it:
2We will solve this problem using arrays and continue with the lottery example on page 175.
156 Meeting 8. Introducing Objects