Skip to content

Commit 1147542

Browse files
author
jsquared21
committed
Add Ex05_34
1 parent 0516364 commit 1147542

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Binary file not shown.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
(Game: scissor, rock, paper) Programming Exercise 3.17 gives a program that
3+
plays the scissor-rock-paper game. Revise the program to let the user continuously
4+
play until either the user or the computer wins more than two times than its
5+
opponent.
6+
*/
7+
import java.util.Scanner;
8+
9+
public class Exercise_05_34 {
10+
public static void main(String[] args) {
11+
Scanner input = new Scanner(System.in);
12+
13+
int computerWins, // Counts he number of computer Wins
14+
userWins; // Counts the number of users Wins
15+
computerWins = userWins = 0; // Set acummulators to 0
16+
17+
do {
18+
// Generate a random integer 0, 1, or 2
19+
int computer = (int)(Math.random() * 3);
20+
21+
// Prompt the user to enter a number 0, 1, or 2
22+
System.out.print("scissor (0), rock(1), paper (2): ");
23+
int user = input.nextInt();
24+
25+
System.out.print("The computer is ");
26+
switch (computer)
27+
{
28+
case 0: System.out.print("scissor."); break;
29+
case 1: System.out.print("rock."); break;
30+
case 2: System.out.print("paper."); break;
31+
}
32+
33+
System.out.print(" You are ");
34+
switch (user)
35+
{
36+
case 0: System.out.print("scissor"); break;
37+
case 1: System.out.print("rock"); break;
38+
case 2: System.out.print("paper"); break;
39+
default : System.out.println(
40+
"disqualified for entering an invalid number.");
41+
System.exit(1);
42+
}
43+
44+
// Display result
45+
if (computer == user)
46+
System.out.println(" too, It is a draw");
47+
else
48+
{
49+
boolean win = (user == 0 && computer == 2) ||
50+
(user == 1 && computer == 0) ||
51+
(user == 2 && computer == 1);
52+
if (win)
53+
{
54+
System.out.println(". You won");
55+
computerWins++; // Increment computer wins
56+
}
57+
else
58+
{
59+
System.out.println(". You lose");
60+
userWins++; // Increment user wins
61+
}
62+
63+
}
64+
// Print Score
65+
System.out.println("Computer wins: " + computerWins +
66+
"\nUser wins: " + userWins);
67+
68+
// If either the user or the computer wins
69+
// are less than or equal to 2 continue play.
70+
} while (Math.abs(computerWins - userWins) <= 2);
71+
}
72+
}

0 commit comments

Comments
 (0)