Java Reference
In-Depth Information
Method
winning
Object
To decide the winner of the game, you look at the players' selections and then at the
rules of the game. For example, if one player chooses
ROCK
and another chooses
PAPER
, the player who chose
PAPER
wins. In other words, the winning object is
PAPER
. The method
winningObject
, given two objects, decides and returns the
winning object. Clearly, this method has two parameters of the type
RockPaperScissors
, and the value returned by this method is also of the type
RockPaperScissors
. The definition of this method is:
public static
RockPaperScissors winningObject
(RockPaperScissors play1,
RockPaperScissors play2)
{
if
((play1 == RockPaperScissors.ROCK &&
play2 == RockPaperScissors.SCISSORS)
|| (play2 == RockPaperScissors.ROCK &&
play1 == RockPaperScissors.SCISSORS))
return
RockPaperScissors.ROCK;
else if
((play1 == RockPaperScissors.ROCK &&
play2 == RockPaperScissors.PAPER)
|| (play2 == RockPaperScissors.ROCK &&
play1 == RockPaperScissors.PAPER))
return
RockPaperScissors.PAPER;
else
return
RockPaperScissors.SCISSORS;
}
After the game is over, this method outputs the final results—that is, the total number
of plays and the number of plays won by each player. The total number of plays is
stored in the variable
gameCount
, the number of plays by player 1 is stored in the
variable
winCount1
, and the number of plays won by player 2 is stored in the
variable
winCount2
. This method has three parameters corresponding to these three
variables. Essentially, the definition of this method is as follows:
Method
display
Results
public static void
displayResults(
int
gCount,
int
wCount1,
int
wCount2)
{
System.out.println("The total number of plays: "
+ gCount);
System.out.println("The number of plays won by "
+ "player 1: " + wCount1);
System.out.println("The number of plays won by "
+ "player 2: " + wCount2);
}
We are now ready to write the algorithm for the method
main
.
Search WWH ::
Custom Search