用java编写一个程序,实现剪刀石头布小游戏:编写一个剪刀石头布游戏的程序。程序启动后会随机生成0~2的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行3轮的游戏,赢的次数多的一方为赢家。若三局皆为平局,则最终结果判为平局。
时间: 2024-09-24 09:27:51 浏览: 57
使用C++程序实现的石头剪刀布游戏代码(调试通过)
4星 · 用户满意度95%
```java
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int playerScore = 0;
int computerScore = 0;
int rounds = 3;
for (int i = 0; i < rounds; i++) {
System.out.println("请输入剪刀、石头或布:");
String playerChoice = scanner.nextLine().trim();
int computerChoice = random.nextInt(3); // 生成0~2的随机数
if (playerChoice.equals("剪刀")) {
playerChoice = "0";
} else if (playerChoice.equals("石头")) {
playerChoice = "1";
} else if (playerChoice.equals("布")) {
playerChoice = "2";
} else {
System.out.println("无效输入,请重新输入剪刀、石头或布。");
i--; // 重新进行这一轮
continue;
}
System.out.println("电脑选择了:" + getChoiceName(computerChoice));
if (playerChoice.equals(String.valueOf(computerChoice))) {
System.out.println("平局!");
} else if ((playerChoice.equals("0") && computerChoice == 2) ||
(playerChoice.equals("1") && computerChoice == 0) ||
(playerChoice.equals("2") && computerChoice == 1)) {
System.out.println("你赢了这一轮!");
playerScore++;
} else {
System.out.println("电脑赢了这一轮!");
computerScore++;
}
}
if (playerScore > computerScore) {
System.out.println("恭喜你赢得了游戏!");
} else if (playerScore < computerScore) {
System.out.println("很遗憾,电脑赢得了游戏。");
} else {
System.out.println("游戏结束,双方平局!");
}
}
private static String getChoiceName(int choice) {
switch (choice) {
case 0: return "剪刀";
case 1: return "石头";
case 2: return "布";
default: return "";
}
}
}
```
阅读全文