Java Reference
In-Depth Information
public static int bestPick(int remain, int maxPick) {
if (remain <= maxPick) return remain - 1; //put user in losing position
int r = remain % (maxPick + 1);
if (r == 0) return maxPick; //put user in losing position
if (r == 1) return random(1, maxPick); //computer in losing position
return r - 1; //put user in losing position
} //end bestPick
public static int random(int m, int n) {
//returns a random integer from m to n, inclusive
return (int) (Math.random() * (n - m + 1)) + m;
} //end random
} //end class Nim
Note the use of the
do...while
statement for getting and validating the user's play. The general form is as follows:
do <statement> while (<expression>);
As usual,
<statement>
can be simple (one-line) or compound (enclosed in braces). The words
do
and
while
and
the brackets and semicolon are required. The programmer supplies
<statement>
and
<expression>
. A
do...while
is
executed as follows:
1.
<statement>
is executed.
2.
<expression>
is then evaluated; if it is
true
, repeat from step 1. If it is
false
, execution
continues with the statement, if any, after the semicolon.
As long as
<expression>
is
true
,
<statement>
is executed. It is important to note that because of the nature of
the construct,
<statement>
is
always executed at least once
. This is particularly useful in a situation where we want
<statement>
to be executed at least once. In this example, we need to prompt the user at least once for his play, hence
the reason for
do...while
.
The following is a sample run of Program P6.4:
Number of matches on the table?
30
Maximum pickup per turn?
5
Matches remaining: 30
Your turn:
2
Matches remaining: 28
I pick up 3
Matches remaining: 25
Your turn:
3
Matches remaining: 22
I pick up 3
Matches remaining: 19
Your turn:
6
Invalid: must be between 1 and 5
Your turn:
1
Matches remaining: 18
I pick up 5
Matches remaining: 13
Search WWH ::
Custom Search