java人机猜拳代码
时间: 2024-04-14 18:23:42 浏览: 99
Java人机猜拳
当然可以!以下是一个简单的Java人机猜拳代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
String[] choices = {"石头", "剪刀", "布"};
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("欢迎来到猜拳游戏!请选择:");
System.out.println("1. 石头");
System.out.println("2. 剪刀");
System.out.println("3. 布");
int userChoice = scanner.nextInt();
int computerChoice = random.nextInt(3) + 1;
System.out.println("你选择了:" + choices[userChoice - 1]);
System.out.println("电脑选择了:" + choices[computerChoice - 1]);
if (userChoice == computerChoice) {
System.out.println("平局!");
} else if ((userChoice == 1 && computerChoice == 2) ||
(userChoice == 2 && computerChoice == 3) ||
(userChoice == 3 && computerChoice == 1)) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
}
}
```
这个代码实现了一个简单的人机猜拳游戏。用户通过输入数字选择石头、剪刀或布,电脑随机生成一个选择,然后比较两者的选择来判断胜负。
阅读全文