用java实现剪刀石头布
时间: 2023-09-30 17:07:51 浏览: 87
以下是Java实现剪刀石头布的示例代码:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int playerScore = 0;
int computerScore = 0;
int numGames = 0;
System.out.println("Let's play Rock-Paper-Scissors!");
while (true) {
System.out.print("Enter your move (rock, paper, or scissors): ");
String playerMove = input.nextLine().toLowerCase();
if (!playerMove.equals("rock") && !playerMove.equals("paper") && !playerMove.equals("scissors")) {
System.out.println("Invalid move. Please try again.");
continue;
}
int computerMove = (int) (Math.random() * 3); // 0 = rock, 1 = paper, 2 = scissors
String computerMoveStr = "";
if (computerMove == 0) {
computerMoveStr = "rock";
} else if (computerMove == 1) {
computerMoveStr = "paper";
} else {
computerMoveStr = "scissors";
}
System.out.println("Computer chose " + computerMoveStr + ".");
if (playerMove.equals(computerMoveStr)) {
System.out.println("Tie!");
} else if (playerMove.equals("rock") && computerMoveStr.equals("scissors")
|| playerMove.equals("paper") && computerMoveStr.equals("rock")
|| playerMove.equals("scissors") && computerMoveStr.equals("paper")) {
System.out.println("You win!");
playerScore++;
} else {
System.out.println("Computer wins!");
computerScore++;
}
numGames++;
System.out.println("Your score: " + playerScore + ", Computer score: " + computerScore);
System.out.print("Play again? (y/n): ");
String playAgain = input.nextLine().toLowerCase();
if (!playAgain.equals("y")) {
break;
}
}
System.out.println("Thanks for playing! Final score - Your score: " + playerScore
+ ", Computer score: " + computerScore + ", Number of games played: " + numGames);
}
}
```
这个程序通过使用 `Scanner` 来获取玩家输入,然后使用 `Math.random()` 生成计算机的随机选择。然后,它使用一系列 `if` 语句来比较玩家和计算机的选择,并输出结果。程序还跟踪每个玩家和计算机的得分,以及游戏的总次数。
阅读全文