Java Reference
In-Depth Information
1 private Currency getRandomCoinValue () {
2
double randomNumber = Math . random( ) ;
3
if (randomNumber < 0.25) {
4
return Currency .PENNY;
5
}
6
if (randomNumber < 0.5 && randomNumber > = 0.25) {
7
return Currency .NICKEL;
8
}
9
if (randomNumber < 0.75 && randomNumber > = 0.50) {
10
return Currency .DIME;
11
}
if (randomNumber > = 0.75) {
12
13
return C u r r e n c y . QUARTER ;
14
}
15
}
However, the extra conditions are unnecessary. For example, if Java is executing Line 6,
then it must be the case that randomNumber >= 0.25 . If this was not the case, then the
condition at Line 3 would have fired and the return statement would have terminated the
method (i.e., we would have never reached Line 6). This means that the original method
returns each of the four coin values with equal probability.
Let us now present the Change class. The class can contain several coins, which we
will store using an ArrayList . The class will have appropriate constructors, a method for
converting the change to a string, and a method that evaluates the value of the change. The
last method will return the sum of all the coins that are tails.
public class Change
{
ArrayList < Coin > coins = new ArrayList < Coin > () ;
public Change () {}
public Change( int count) {
for ( int i=0;i < count ;
i++) {
coins .add( new Coin() ) ;
}
}
public Change(ArrayList
<
Currency
>
values)
{
for (Currency value : values )
{
coins .add( new Coin( value ) ) ;
}
}
public void flipAllCoins()
{
for (Coin c : coins)
{
c. flip();
}
}
public void flipSomeCoins(ArrayList < Integer > indexes)
{
for ( int i
: indexes)
{
coins .get( i ) . flip () ;
}
}
 
Search WWH ::




Custom Search