编写简单的“剪刀石头布”游戏,电脑随机产生剪刀、石头还是布,用户输入,最终比较结果。java
时间: 2023-12-29 12:04:24 浏览: 122
java开发的石头、剪刀、布游戏源码
好的,以下是Java代码实现:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int computerChoice = (int) (Math.random() * 3); // 生成0、1、2三个数,分别代表剪刀、石头、布
System.out.print("请出拳(0代表剪刀,1代表石头,2代表布):");
int userChoice = input.nextInt();
System.out.print("电脑出拳:");
switch (computerChoice) {
case 0:
System.out.println("剪刀");
break;
case 1:
System.out.println("石头");
break;
case 2:
System.out.println("布");
break;
}
System.out.print("你出拳:");
switch (userChoice) {
case 0:
System.out.println("剪刀");
break;
case 1:
System.out.println("石头");
break;
case 2:
System.out.println("布");
break;
}
if (computerChoice == userChoice) {
System.out.println("平局!");
} else if ((computerChoice == 0 && userChoice == 2) || (computerChoice == 1 && userChoice == 0)
|| (computerChoice == 2 && userChoice == 1)) {
System.out.println("你输了!");
} else {
System.out.println("你赢了!");
}
}
}
```
程序运行效果如下:
```
请出拳(0代表剪刀,1代表石头,2代表布):1
电脑出拳:剪刀
你出拳:石头
你赢了!
```
阅读全文