【Java学习笔记】20.Properties实现付费功能案例

1.Properties介绍
实现map接口本质是一个map集合
Properties:Properties 类表示了一个持久的属性集。属性列表中每个键及其对应值都是一个字符串。
特点:Properties 可保存在流中或从流中加载。
2、功能
A:添加元素

public Object setProperty(String key,String value)

获取元素

public String getProperty(String key)
public Set<String> stringPropertyNames()

3.游戏案例
案例:我有一个猜数字小游戏的程序,请写一个程序实现在测试类中只能用5次,
超过5次提示:游戏试玩已结束,请付费。

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Scanner;

public class Game {
    public static void main(String[] args) throws IOException {

        //创建Properties对象并加载gameCount.txt文件
        Properties prop = new Properties();
        prop.load(new FileReader("gameCount.txt"));
        //取出当前游戏次数
        int count = Integer.parseInt(prop.getProperty("count"));
        if ( count <= 5){
            prop.setProperty("count", String.valueOf(++count));
            startGame();
            prop.store(new FileWriter("gameCount.txt"),null);
        }else{
            System.out.println("游戏试玩已结束,请付费使用");
        }

    }

    public static void startGame(){
        //生成1~100以内的随即数字
        int number = (int)(Math.random()*10) + 1;
        while (1 == 1){
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入你所猜测的数字:");
            int guess = sc.nextInt();
            if ( guess > number){
                System.out.println("数字大了");
            }else if ( guess < number){
                System.out.println("数字小了");
            }else {
                System.out.println("恭喜你猜对了!");
                break;
            }
        }
    }
}

gameCount.txt

count=0

游戏结果
这里写图片描述这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值