java程序:剪刀石头布:“剪刀石头布”的游戏相信大家都不陌生,本案例要求编写一个剪刀石头布游戏的程序。程序启动后会随机生成1~3的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行5轮的游戏,赢的次数多的一方为赢家。若五局皆为平局,则最终结果判为平局。
时间: 2023-12-29 20:04:25 浏览: 163
好的,我可以帮你解答这个问题。以下是 Java 代码实现:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int computerScore = 0;
int playerScore = 0;
for (int i = 1; i <= 5; i++) {
int computerChoice = (int) (Math.random() * 3) + 1;
System.out.print("Round " + i + ": ");
System.out.print("Enter 1 for rock, 2 for paper, or 3 for scissors: ");
int playerChoice = input.nextInt();
if (computerChoice == playerChoice) {
System.out.println("It's a tie!");
} else if ((computerChoice == 1 && playerChoice == 3) ||
(computerChoice == 2 && playerChoice == 1) ||
(computerChoice == 3 && playerChoice == 2)) {
System.out.println("Computer wins!");
computerScore++;
} else {
System.out.println("Player wins!");
playerScore++;
}
}
if (computerScore == playerScore) {
System.out.println("It's a tie!");
} else if (computerScore > playerScore) {
System.out.println("Computer wins the game!");
} else {
System.out.println("Player wins the game!");
}
}
}
```
这个程序使用了一个 for 循环来进行5轮的游戏,每一轮中会随机生成电脑的选择,并要求玩家输入自己的选择。然后根据规则判断胜负,并记录分数。5轮结束后,根据分数判断最终胜负。
阅读全文