Chapter 3 - Selections
- Class 1:
- Class 2:
- Class 3:
In-class exercise: Rock-Paper-Scissors
(text exercise 3.17 modified) Call your program
RockPaperScissors.java.
Input: an integer 0, 1, or 2, representing a play of "rock", "paper",
or "scissors", respectively.
Output:
- Before the input: a prompt "Please enter 0 (rock), 1 (paper), or
2 (scissors): "
- After the input:
- The computer randomly chooses an integer to represent it's play.
- Print "I played <play>." where <play> is
"rock"/"paper"/"scissors" depending on the computer's randomly chosen
integer.
- Print "You win."/"You lose."/"Draw." based on the following rules:
- Rock wins against scissors.
- Scissors wins against paper.
- Paper wins against rock.
- Players that choose the same play draw (i.e. tie).
Hint: At no point should you have an if-else chain for 9 cases.
Each of the last two print statements should require at most 3 cases
each. Let the user's play be p1 and the computer's play be p2.
Consider what value you get if you compute (p1 - p2 + 3) % 3. How
does the result of this computation map to the win/lose/draw
cases? Why does this work? Why wouldn't the expression (p1 - p2) % 3 suffice for our three cases?
Example transcripts (input underlined):
Please enter 0 (rock), 1 (paper), or 2 (scissors): 0
I played paper.
You lose.
Please enter 0 (rock), 1 (paper), or 2 (scissors): 1
I played rock.
You win.
Please enter 0 (rock), 1 (paper), or 2 (scissors): 2
I played scissors.
Draw.
© Todd W. Neller