在Java中实现石头剪刀布游戏,可以采用以下几种方法:
方法一:使用`Random`类
这种方法通过生成随机数来决定计算机的出拳,并比较用户和计算机的出拳结果。
```java
import java.util.Random;
import java.util.Scanner;
public class GuessGame {
public static void main(String[] args) {
String[] moves = {"石头", "剪刀", "布"};
Scanner sc = new Scanner(System.in);
Random random = new Random();
System.out.println("欢迎来到猜拳游戏!(五局三胜制)");
int win = 0;
int lose = 0;
int draw = 0;
int i = 1;
while (win < 3 && lose < 3 && draw + win + lose != 5) {
System.out.println("==========");
System.out.println("请出拳(1-石头, 2-剪刀, 3-布):");
int userChoice = sc.nextInt();
int computerChoice = random.nextInt(3) + 1;
System.out.println("电脑出拳: " + moves[computerChoice - 1]);
if (userChoice == computerChoice) {
System.out.println("平局");
draw++;
} else if ((userChoice - computerChoice) % 3 == 1) {
System.out.println("你赢了!");
win++;
} else {
System.out.println("你输了!");
lose++;
}
i++;
}
if (win == 3) {
System.out.println("恭喜你赢得了比赛!");
} else if (lose == 3) {
System.out.println("很遗憾,你输了比赛!");
} else {
System.out.println("比赛结束,平局次数: " + draw);
}
sc.close();
}
}
```
方法二:使用`Scanner`类获取用户输入
这种方法通过用户输入来决定出拳,并比较用户和计算机的出拳结果。
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
String[] moves = {"石头", "剪刀", "布"};
Scanner sc = new Scanner(System.in);
System.out.println("欢迎来到石头剪刀布游戏!");
System.out.println("请输入你的出拳(1-石头, 2-剪刀, 3-布):");
int userChoice = sc.nextInt();
int computerChoice = (int) (Math.random() * 3) + 1;
System.out.println("电脑出拳: " + moves[computerChoice - 1]);
if (userChoice == computerChoice) {
System.out.println("平局");
} else if ((userChoice - computerChoice) % 3 == 1) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
sc.close();
}
}
```
方法三:使用`switch`语句
这种方法通过用户输入和`switch`语句来决定出拳,并比较用户和计算机的出拳结果。