剪刀石头布java用while循环语句
时间: 2024-09-06 09:01:20 浏览: 57
Java剪刀石头布小游戏源码整理
剪刀石头布游戏通常可以用Java的while循环来实现基本的交互流程。以下是一个简单的例子,它展示了如何通过用户输入和随机生成电脑选择来进行游戏:
```java
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("欢迎来到剪刀石头布游戏!请输入你的选择 (1 石头, 2 布, 3 剪刀):");
while (true) {
int playerChoice = scanner.nextInt() - 1; // 将1、2、3转换为0、1、2
int computerChoice = random.nextInt(3); // 电脑的选择范围从0到2
if (playerChoice == computerChoice) {
System.out.println("平局,双方都选择了" + (playerChoice + 1));
} else if ((playerChoice == 0 && computerChoice == 2) ||
(playerChoice == 1 && computerChoice == 0) ||
(playerChoice == 2 && computerChoice == 1)) {
System.out.println("你赢了!电脑出了" + (computerChoice + 1) + "," + (playerChoice + 1) + "胜过");
} else {
System.out.println("你输了!电脑出了" + (computerChoice + 1) + ", 而你出的是" + (playerChoice + 1));
}
System.out.print("再来一局吗?请输入Y继续(N结束): ");
String playAgain = scanner.nextLine().toLowerCase();
if (!playAgain.equals("y")) {
break;
}
}
scanner.close();
}
}
```
阅读全文