1 package randomzxw;
2
3 import java.util.Scanner;
4
5 enum EnumGuess {
6 //定义剪刀,石头,布。三个元素;
7 剪刀("剪刀",1),石头("石头",2),布("布",3);
8 private String name;
9 private int index;
10 //构造函数
11 private EnumGuess(String name,int index){
12 this.name=name;
13 this.index=index;
14 }
15 //获取索引
16 public int getIndex(){
17 return this.index;
18 }
19 //通过索引,用于提取用户、电脑输出的值;
20 public String getName(int index){
21 for(EnumGuess e:EnumGuess.values()){
22 if(e.getIndex()==index){
23 return e.name;
24 }
25 }
26 return null;
27 }
28 }
29 public class guess1 {
30 public static void main(String[] args){
31 Scanner sc=new Scanner(System.in);
32 System.out.println("请出拳 1-剪刀 2-石头 3-布");
33 //用户输入
34 int cs1=sc.nextInt();
35 //电脑随机值
36 int cs2=(int)(Math.random()*10)%3+1;
37 //将,剪刀石头布看成是一个循环队列,1->2->3 => 1=4-3 => 2=5-3 => 3=6-3;
38 //用户值:1;电脑1、2、3,则temp=cs1-cs2的值为1-1=0:平局;1-2=-1:输;1-3=4-3=1:赢;
39 //用户值:2;电脑1、2、3,则temp=cs1-cs2的值为2-2=0:平局;2-3=-1:输;2-1=1:赢;
40 //用户值:3;电脑1、2、3,则temp=cs1-cs2的值为3-3=0:平局;3-1=3-4=-1:输;3-2=1:赢;
41 if(cs1-cs2==2){
42 cs2+=3;
43 }else if(cs1-cs2==-2){
44 cs1+=3;
45 }
46 int temp=cs1-cs2;
47 EnumGuess guess = EnumGuess.剪刀;
48 switch(temp){
49 case 1:
50 System.out.println("你出的是 " + guess.getName(cs1>3?cs1-3:cs1) + "
电脑出的是 " + guess.getName(cs2>3?cs2-3:cs2) + "
你赢啦");
51 break;
52 case 0:
53 System.out.println("你出的是 " + guess.getName(cs1>3?cs1-3:cs1) + "
电脑出的是 " + guess.getName(cs2>3?cs2-3:cs2) + "
平局啦");
54 break;
55 case -1:
56 System.out.println("你出的是 " + guess.getName(cs1>3?cs1-3:cs1) + "
电脑出的是 " + guess.getName(cs2>3?cs2-3:cs2) + "
你输啦");
57 break;
58 }
59 }
60 }