Java Reference
In-Depth Information
this .bias = bias;
flip();
} public void flip() {
f a c e = (Math . random ( ) < bias) ? true : false ; // true is heads
} public String toString() {
switch (value) {
case 1:
return "penny that is " +(( face )? "heads" : "tails" );
case 5:
return "nickel that is " +(( face )? "heads" : "tails" );
case 10:
return "dime that is " +(( face )? "heads" : "tails" );
case 25:
return "quarter that is " +(( face )? "heads" : "tails" );
default :
return "" ;
}
} private int getRandomCoinValue () {
double randomNumber = Math . random( ) ;
if (randomNumber < 0.25) {
return 1;
if (randomNumber < 0.5) {
return 5;
if (randomNumber < 0.75) {
return 10;
return 25;
} public int getValue () {
return value ;
public boolean isHeads () {
return face ;
}
} Note that we have defined the default value of 0.5 for the bias of the coin. Note as well
that the switch statement inside the toString method does not need break statements.
The reason is that the return statement terminates the execution of the method. Note
that the default construct inside the switch is needed for the program to compile. If it is
missing, then Java will not know what to return if value does not match one of the cases
that are enumerated. Finally, note that the flip method calls the Math.random method,
which in turn returns a real number between 0 (inclusive) and 1 (exclusive). Suppose that
the bias is 0.7. This means that there is a 70% chance that we will get heads. If our random
number is smaller than 0.7, then the face of the coin will be heads. Otherwise, the face of
the coin will be tails.
Although elegant, the above design can be improved. One problem with the design is
that nothing prevents us from assigning an arbitrary number, for example 37, to the variable
value . However, we all know that there is no coin that is 37 cents. Another shortcoming
is that the toString method is a little clunky because it needs to go through all possible
 
Search WWH ::




Custom Search