以前用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)