Java中IF的使用简单实现剪刀石头布猜拳小游戏

这里我暂且定义数字“1”为剪刀,“2”为石头,“3”为布。很容易得出:

1>3
2>1

3>2

然后根据这个写的代码,可以在控制台运行:

import java.util.Scanner;
public class helloWorld {
    public static void main(String[] args) {
        int sr = 0;
        int u=0;                                      //定义变量储存胜场
        System.out.println("猜拳,1是剪刀,2是石头,3是布,输入888退出游戏");
        while (sr != 888) {
            int sj = (int) (1 + Math.random() * 3);   //生成随机数,即电脑出拳
            Scanner input = new Scanner(System.in);
            System.out.print("\nPlease enter:");
            sr = (int) input.nextDouble();            //输入值,即自己出拳
            if (sj == sr) {
                System.out.println("平局,胜场"+ u);    //平局
            } else if ((sj == 1 && sr == 3) || (sj == 3 && sr == 1)) {    //出现1>3场景,即剪刀>布
                if (sj == 1) {
                    System.out.println("电脑赢,ta是"+sj);
                } else if (sr == 1) {
                    System.out.println("你赢了,ta是"+sj+"胜场"+ ++u);
                }
            }
           else if(sr==888){
                break;                                //如果输入888程序退出运行
            }
            else {
                if (sj > sr) {                        //除去特例1>3,其它情况正常比较数值
                    System.out.println("电脑赢,ta是"+sj);
                } else {
                    System.out.println("你赢了,ta是"+sj+"胜场"+ ++u);
                }
            }
        }
        System.out.println("您已退出!");
    }
}

猜你喜欢

转载自blog.csdn.net/u014238498/article/details/80423791