JAVA 猜拳小游戏

以前用C++写了个猜拳小游戏,这次做个JAVA版的…C++版的在这里→http://blog.csdn.net/lingle77/article/details/41421769

又想起了已经离开的213同学。


代码如下

import java.util.Scanner;

public class PlayGame {
	public static void main(String[] args) {
		System.out.print("scissor(0), rock(1), paper(2) :");
		int computer = (int) (Math.random() * 3);
		Scanner in = new Scanner(System.in);
		int user = in.nextInt();
		switch (computer) {
		case 0:
			System.out.print("The computer is scissor.");
			break;
		case 1:
			System.out.print("The computer is rock.");
			break;
		case 2:
			System.out.print("The computer is paper.");
			break;
		}
		System.out.print((user == 0) ? "You are scissor."
				: (user == 1) ? "You are rock."
						: (user == 2) ? "You are paper."
								: "\nInput error, please re-enter.");
		if (user == computer) {
			System.out.println(",the same with computer.It is draw.");
		} else if (user == ++computer || (user == 0 && computer == 2)) {
			System.out.println("You win.");
		} else if (user >= 0 && user <= 3)
			System.out.println("You lose.");
	}
}

运行结果

scissor(0), rock(1), paper(2) :0
The computer is paper.You are scissor.You lose.

scissor(0), rock(1), paper(2) :1
The computer is scissor.You are rock.You win.

总算刷了个平局出来:

scissor(0), rock(1), paper(2) :2
The computer is paper.You are paper.,the same with computer.It is draw.


scissor(0), rock(1), paper(2) :6
The computer is paper.
Input error, please re-enter.


学习心得

要产生随机数,可以使用Java api中java.lang包中的Math类.Math类以静态方法的方式提供常用的数学方法,
其中Math.random()方法是一个可以产生[0.0,1.0]区间内的一个双精度浮点数的方法
如:
产生一个100以内的整数:int x=(int)(Math.random()*100);
又如:
产生一个1-50之间的随机数:int x=1+(int)(Math.random()*50)



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值