使用IO流技术和Properties集合限制猜数字游戏程序只能运行3次

1. 请使用IO流技术和Properties集合限制猜数字游戏程序只能运行3次

public class Test02 {
    public static void main(String[] args) throws IOException {
        System.out.println();
        //2、创建配置文件times.properties对应的File对象
        File configFile = new File("day13\\src\\times.properties");
        //3、如果配置文件不存在,则创建文件
        if (!configFile.exists()) {
            configFile.createNewFile();
        }
        //4、创建Properties对象
        Properties props = new Properties();
        //5、把配置文件中的内容加载到Properties对象中
        props.load(new FileInputStream(configFile));
        //6、获取键times对应的值,表示程序已经运行的次数
        String times = props.getProperty("times");
        //7、根据times的值提示剩余机会并调用猜数字方法,times的值为3,不调用猜数字方法,直接退出JVM
        if(times!=null&&times.equals("3")) {
            System.out.println("您的免费试用3次机会用完,请充值~");
            //退出虚拟机
            System.exit(0);
        } else {
            System.out.println("您的免费试用机会剩余: "+(3-(times==null? 0: Integer.parseInt(times)))+" 次,请珍惜~~");
            //调用方法,完成猜数字
            guessNum();
        }

        //8、如果times为null,说明第一次运行,向Properties集合对象存储键值对times=1
        if(times==null) {
           props.setProperty("times","1");
        } else {
            //9、如果times不为null,说明不是第一次运行,向Properties集合对象存储键值对times=原有次数+1
            props.setProperty("times",Integer.parseInt(times)+1+"");
        }
        //10、把Properties中的内容写入到文件
        props.store(new FileOutputStream(configFile),null);

    }
    //1、为了方便使用,把之前猜数字案例的代码定义成方法
    public static void guessNum() {
        //1.1、创建Random对象
        Random r = new Random();

        //1.2、使用Random对象生成一个1-100(包含1,包含100)之间的数字,保存在int变量guessNum
        int guessNum = r.nextInt(100) + 1;

        //1.3、创建Scanner对象
        Scanner sc = new Scanner(System.in);

        //1.6、通过分析,发现: 步骤4-5应该是一个循环的过程,但是次数不确定,使用while(true)
        while(true) {
            //1.4、获取键盘录入的用户猜测的数字,保存在int变量inputNum中
            System.out.println("请输入一个整数(1到100之间): ");
            int inputNum = sc.nextInt();

            //1.5、使用if第三种格式,对inputNum和guessNum中的值进行比较
            if(inputNum>guessNum) {
                //1.5.1、如果 inputNum>guessNum  提示 "大了"
                System.out.println("大了");
            } else if(inputNum<guessNum) {
                //1.5.2、否则,如果 inputNum<guessNum  提示 "小了"
                System.out.println("小了");
            } else {
                //1.5.3、否则 提示 "恭喜你猜对了"
                System.out.println("恭喜你猜对了");
                break;//结束while循环
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值