import java.util.Random;
import java.util.Scanner;
public class BreakDemo {
public static void main(String[] args) {
System.out.println("三局两胜制");
String[] arr = {"剪刀","石头","布"};//0 1 2 arr[index]
Scanner input = new Scanner(System.in);
//用户赢得次数 电脑赢得次数
int usrCount = 0;
int comCount = 0;
while (true) {
//1.获取一个数字0~2
System.out.print("剪刀(0) 石头(1) 布(2):");
int usr = input.nextInt();
//2.随机一个数字
Random random = new Random();
//调用random类,将随机数(1~3)赋值给com
int com = random.nextInt(3);
//3.开始比较
if (usr == com) {
//平局
System.out.println("用户是" + arr[usr] + ",电脑是" + arr[com] + ",平局");
} else if (usr - com == 1 || usr - com == -2) {
//用户赢
System.out.println("用户是" + arr[usr] + ",电脑是" + arr[com] + ",用户赢");
usrCount++;
} else {
//电脑赢
System.out.println("用户是" + arr[usr] + ",电脑是" + arr[com] + ",电脑赢");
comCount++;
}
if (usrCount == 2 || comCount == 2) {
break;
}
}
if (usrCount == 2) {
System.out.println("最终,用户胜利!");
} else {
System.out.println("最终,电脑胜利!");
}
}
}
上述中定义了一个字符串数组,并将“石头,剪刀,布”存入数组,在比较中并没有使用数组的元素来比较是否相同,因为字符串的比较会比int类型比较更麻烦。