用Java中的for语句编写程序:一个剪刀石头布游戏的程序。程序启动后会随机生成1~3的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行5轮的游戏,赢的次数多的一方为赢家。若五局皆为平局,则最终结果判为平局。
时间: 2024-09-06 20:01:35 浏览: 45
当然,我可以帮你创建一个简单的Java程序来模拟剪刀石头布游戏。这里是一个基础版本的代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int userWins = 0;
int computerWins = 0;
for (int i = 1; i <= 5; i++) {
System.out.println("Round " + i + ":");
// 电脑随机选择
int computerChoice = random.nextInt(4) + 1;
if (computerChoice == 1) {
System.out.println("Computer chose Scissors.");
} else if (computerChoice == 2) {
System.out.println("Computer chose Paper.");
} else {
System.out.println("Computer chose Stone.");
}
// 玩家输入选择
System.out.println("Choose (1 for Scissors, 2 for Paper, 3 for Stone):");
int userChoice = input.nextInt();
// 判断胜负
switch (userChoice) {
case 1:
if (computerChoice == 2) {
System.out.println("You lose! Paper covers Scissors.");
computerWins++;
} else if (computerChoice == 3) {
System.out.println("You win! Scissors cut Stone.");
userWins++;
} else {
System.out.println("It's a tie!");
}
break;
case 2:
if (computerChoice == 1) {
System.out.println("You win! Paper covers Scissors.");
userWins++;
} else if (computerChoice == 3) {
System.out.println("You lose! Stone beats Paper.");
computerWins++;
} else {
System.out.println("It's a tie!");
}
break;
case 3:
if (computerChoice == 1) {
System.out.println("You lose! Scissors cut Stone.");
computerWins++;
} else if (computerChoice == 2) {
System.out.println("You win! Stone beats Paper.");
userWins++;
} else {
System.out.println("It's a tie!");
}
break;
default:
System.out.println("Invalid choice. Please try again.");
}
System.out.println("Score: You - " + userWins + ", Computer - " + computerWins);
}
if (userWins > computerWins) {
System.out.println("Congratulations! You are the winner!");
} else if (userWins < computerWins) {
System.out.println("Sorry, you lost. Better luck next time!");
} else {
System.out.println("It's a draw! Both players have " + userWins + " wins.");
}
}
}
```
运行这个程序后,它会引导你和电脑进行五轮剪刀石头布比赛,并在结束后显示获胜者或平局的结果。
阅读全文