用java编写猜拳游戏
时间: 2023-11-27 14:03:15 浏览: 74
以下是使用Java编写的猜拳游戏示例代码:
```
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] choices = {"rock", "paper", "scissors"};
int computerChoice = (int) (Math.random() * 3);
System.out.print("Enter your choice (rock, paper, or scissors): ");
String userChoice = input.nextLine().toLowerCase();
System.out.println("Computer chose " + choices[computerChoice]);
if (userChoice.equals(choices[computerChoice])) {
System.out.println("It's a tie!");
} else if ((userChoice.equals("rock") && choices[computerChoice].equals("scissors")) ||
(userChoice.equals("paper") && choices[computerChoice].equals("rock")) ||
(userChoice.equals("scissors") && choices[computerChoice].equals("paper"))) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
}
}
}
```
该程序首先生成计算机的随机选择(rock、paper或scissors),然后提示用户输入他们的选择。程序将用户选择与计算机选择进行比较并输出结果。如果用户选择与计算机选择相同,则宣布平局。如果用户选择胜利,则宣布用户获胜。否则,宣布计算机获胜。
阅读全文