java简单的猜数字游戏

时间:2025-03-19 13:04:41
import ;
import ;

public class helloworld {
    public static void main(String[] args) {
        Random r = new Random();
        int x = (100) + 1;//获取1!100之间的随机数
        //如果没有猜中就一直循环
        while (true) {
            //获取键盘录入的数字
            ("请输入您猜的数字");
            Scanner sc = new Scanner();
            int y = ();
            //进行比较
            if (x > y) {
                ("猜小了");
            } else if (x < y) {
                ("猜大了");
            } else {
                ("猜中了");
                break;//猜中了立刻结束循环
            }
        }
    }
}

利用Scanner和random两个类进行实现功能

如果引入保底机制可以添加一个变量作为计数器,用if语句判断是否达到保底次数

import ;
import ;

public class helloworld {
    public static void main(String[] args) {
        Random r = new Random();
        int x = (100) + 1;//获取1!100之间的随机数
        //利用count作为计数器,控制保底数量
        int count = 0;
        //如果没有猜中就一直循环
        while (true) {
            //获取键盘录入的数字
            ("请输入您猜的数字");
            Scanner sc = new Scanner();
            int y = ();
            count++;
            //利用if语句判断是否触发保底次数
            if (count == 3) {
                ("保底成功,猜中了");
                break;
            } else {
                //进行比较
                if (x > y) {
                    ("猜小了");
                } else if (x < y) {
                    ("猜大了");
                } else {
                    ("猜中了");
                    break;//猜中了立刻结束循环
                }
            }
        }
    }
}