Java Reference
In-Depth Information
ArrayList < Integer > result = new ArrayList < Integer > () ;
while ( st . hasMoreTokens () ) {
result .add(Integer .parseInt(st .nextToken()) 1) ;
return result ;
}
}
The code is very similar to the Yahtzee game from the previous chapter. The only difference
is that the convert method now returns an ArrayList instead of an array and that we do
not have to check for a Yahtzee. Here is a possible execution of the program (user input in
italic ).
HEADS HEADS HEADS HEADS QUARTER HEADS PENNY HEADS QUARTER HEADS
Total: 51
Which coins do you want to flip:
123
HEADS NICKEL PENNY HEADS QUARTER HEADS PENNY HEADS QUARTER HEADS
Total: 57
Which coins do you want to flip: 1
HEADS NICKEL PENNY HEADS QUARTER HEADS PENNY HEADS QUARTER HEADS
Total: 57
If we want to make the game more challenging and only allow the user to flip all coins,
then we can rewrite the CoinGame classasfollows.
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) ;
Change change = new Change(10) ;
System. out . println (change) ;
for ( int i=0;i < NUMBER FLIPS ;
i ++)
{
System. out . print ( "Flip all?: " );
if (! keyboard . nextLine () . equals ( "yes" )) {
break ;
change. flipAllCoins() ;
System. out . println (change) ;
}
}
}
Inside the for loop we ask the user if they want to flip all coins. If they do not answer
yes , then we terminate the program. If they answer yes , then we flip all the coins and show
the new coins. This can repeat up to NUMBER FLIPS times. Here is possible execution of the
program
HEADS QUARTER QUARTER HEADS QUARTER NICKEL QUARTER PENNY DIME HEADS
Total : 116
Flip all ?: no
Note that following good programming practices allowed us to change the behavior of the
program by changing very little code. This is the hallmark of an excellent design and this
is what we should strive for when writing software.
 
Search WWH ::




Custom Search