Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1147542

Browse files
author
jsquared21
committed
Add Ex05_34
1 parent0516364 commit1147542

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+
importjava.util.Scanner;
8+
9+
publicclassExercise_05_34 {
10+
publicstaticvoidmain(String[]args) {
11+
Scannerinput =newScanner(System.in);
12+
13+
intcomputerWins,// 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+
intcomputer = (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+
intuser =input.nextInt();
24+
25+
System.out.print("The computer is ");
26+
switch (computer)
27+
{
28+
case0:System.out.print("scissor.");break;
29+
case1:System.out.print("rock.");break;
30+
case2:System.out.print("paper.");break;
31+
}
32+
33+
System.out.print(" You are ");
34+
switch (user)
35+
{
36+
case0:System.out.print("scissor");break;
37+
case1:System.out.print("rock");break;
38+
case2: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+
booleanwin = (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)

[8]ページ先頭

©2009-2025 Movatter.jp