Java (随机数):剪刀、石头、布(三局两胜制)

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类型比较更麻烦。

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值