java1.用程序模拟石头剪刀布,电脑随机出拳,用户通过输入出拳,三局两胜。控制台输出“xx赢了”
时间: 2024-03-08 08:44:23 浏览: 67
可以使用Java编写一个程序来模拟石头剪刀布游戏,以下是一个简单的实现示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
int userScore = 0;
int computerScore = 0;
int rounds = 0;
while (userScore < 2 && computerScore < 2) {
System.out.println("请输入你的选择(1-石头,2-剪刀,3-布):");
Scanner scanner = new Scanner(System.in);
int userChoice = scanner.nextInt();
int computerChoice = generateComputerChoice();
System.out.println("电脑选择了:" + getChoiceName(computerChoice));
int result = compareChoices(userChoice, computerChoice);
if (result == 1) {
userScore++;
System.out.println("你赢了这局!");
} else if (result == -1) {
computerScore++;
System.out.println("电脑赢了这局!");
} else {
System.out.println("这局平局!");
}
rounds++;
}
if (userScore > computerScore) {
System.out.println("你赢了比赛!");
} else {
System.out.println("电脑赢了比赛!");
}
}
private static int generateComputerChoice() {
Random random = new Random();
return random.nextInt(3) + 1;
}
private static String getChoiceName(int choice) {
if (choice == 1) {
return "石头";
} else if (choice == 2) {
return "剪刀";
} else {
return "布";
}
}
private static int compareChoices(int userChoice, int computerChoice) {
if (userChoice == computerChoice) {
return 0;
} else if ((userChoice == 1 && computerChoice == 2) ||
(userChoice == 2 && computerChoice == 3) ||
(userChoice == 3 && computerChoice == 1)) {
return 1;
} else {
return -1;
}
}
}
```
阅读全文