Java Reference
In-Depth Information
public int
computeSum()
{
int
sum = 0 ;
for
(Coin c : coins)
{
if
(! c . isHeads () )
{
sum = sum + c . getValue() ;
}
return
sum ;
}
public
String toString()
{
String result =
""
;
for
(Coin c : coins)
{
result = result+c+
""
;
result = result +
" Total: "
+ computeSum() ;
return
result ;
}
}
The empty constructor is included because of the cardinal rule: “If you specify any
constructors, it is always a good idea to include an empty constructor”. If the empty con-
structor is omitted, then existing code that calls the empty default constructor will no longer
compile. The first non-empty constructor generated the number of default coins that are
requested. Note that the value and the face of the coin is chosen randomly inside the
Coin
class. The second non-empty constructor takes as input an
ArrayList
of currency values,
creates the coins, and populates the
coins ArrayList
. Note that, as expected,
new
is called
multiple times in both constructors. It is called once to create the
ArrayList
and then once
for each element of the
ArrayList
. Note as well the elegancy of the for-each
for
statement
in the second non-empty constructor. Since we only want to iterate through the
ArrayList
without modifying it, we can use this template.
While the
flipAllCoins
method flips all coins, the
flipSomeCoins
method only flips
the input coins. Recall that if
a
is an
ArrayList
,
a.get(i)
will return the
i
th
element of
the list. The
computeSum
method sums the value of all the coins that are tails. Similarly,
the
toString
method creates a string from all the coins and their sum. The design looks
very elegant. Every method is self-explanatory.
Finally, let us consider the
CoinGame
class that implements the game.
import
java . util .
;
public class
CoinGame
∗
{
public static final
int
NUMBER FLIPS=2 ;
public static void
main(String [] args)
{
Scanner keyboard =
new
Scanner(System. in) ;
ArrayList
<
Currency
>
currency =
new
ArrayList
<>
() ;
System. out . println (change) ;
for
(
int
i=0;i
<
NUMBER FLIPS ; i ++)
{
System. out . print (
"Which coins do you want to flip: "
);
change . flipSomeCoins ( convert (keyboard . nextLine () )) ;
System. out . println (change) ;
}
}
static
ArrayList
<
Integer
>
convert(String s)
{
StringTokenizer st =
new
StringTokenizer(s) ;