人机猜拳java代码
时间: 2023-12-03 11:02:24 浏览: 86
下面是一个简单的人机猜拳游戏的 Java 代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
String[] choices = {"rock", "paper", "scissors"};
int computerChoiceIndex = random.nextInt(choices.length);
String computerChoice = choices[computerChoiceIndex];
System.out.println("Please enter your choice (rock, paper, or scissors):");
String userChoice = scanner.nextLine().toLowerCase();
if (!userChoice.equals("rock") && !userChoice.equals("paper") && !userChoice.equals("scissors")) {
System.out.println("Invalid choice!");
} else if (userChoice.equals(computerChoice)) {
System.out.println("Tie!");
} else if ((userChoice.equals("rock") && computerChoice.equals("scissors")) ||
(userChoice.equals("paper") && computerChoice.equals("rock")) ||
(userChoice.equals("scissors") && computerChoice.equals("paper"))) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
}
System.out.println("Computer chose " + computerChoice + ".");
}
}
```
该代码首先使用 `java.util.Random` 类生成计算机的选择,然后使用 `java.util.Scanner` 类接收用户输入的选择。接下来,代码根据用户和计算机的选择来判断胜负,并输出结果。最后,代码显示计算机的选择。
阅读全文