1、更改文件中的数据,特定键的值:

需求:我有一个文本文件(user.txt),我知道数据是键值对形式的,但是不知道内容是什么。
   请写一个程序判断是否有“lisi”这样的键存在,如果有就改变其值为”100”
分析:
  A:把文本文件中的数据加载到Properties集合中
  B:获取该集合的键集合
  C:遍历键集合,进行判断是否是lisi键
          是:更改为“100”
          不是:不理
  D:把更改后的集合数据存储到文本中

 public class PropertiesTest1 {

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

         //创建集合
Properties prop = new Properties();
Reader r = new FileReader("user.txt");
//public void load(Reader reader):把文件中的数据读取到集合中
prop.load(r);
r.close(); //遍历集合,获取键集合
//public Set<String> stringPropertyNames()返回此属性列表中的键集,
//其中该键及其对应值是字符串,如果在主属性列表中未找到同名的键,则还包括默认属性列表中不同的键
Set<String> s = prop.stringPropertyNames();
for(String key : s){
if(prop.get(key).equals("lisi")){
prop.setProperty(key, "100");
}
} //把集合中的数据存储到文本中
Writer w = new FileWriter("user.txt");
prop.store(w,"更改后");
w.close(); } }

2、一些游戏,都有试玩次数或者关卡,当玩到特定的次数或者关卡时,就要求付费。。。来试试如何实现:

下面是次数版本,关卡差不多。

需求:

    我有一个猜数字小游戏的程序,请写一个程序实现在测试类中只能用5次,超过5次提示:游戏试玩已结束,请付费。
分析:
    A:创建一个文本文件,里面写一段键值对数据:count=0(不需要程序创建)
    B:创建properties集合,把文本中的数据加载到集合中
    C:获取count键的值
    D:判断次数
        超过5次:提示
        不超过:count键的值+1,并把这段数据重新存储到文本文件中,继续游戏

 public class PropertiesTest2 {

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

         //创建集合
Properties prop = new Properties();
//把文本的数据加载到集合中
Reader r = new FileReader("count.txt");
prop.load(r);
r.close(); //获取count键的值
String value = prop.getProperty("count");
//把字符串的值转换成int,方便判断
int number = Integer.parseInt(value); //对number进行判断
if(number > 5){
System.out.println("试玩次数已到,请付费");
System.exit(0);
}
else{
number ++;
//重新把数据存储到文本中 //number必须转成字符串
prop.setProperty("count", String.valueOf(number));
Writer w = new FileWriter("count.txt");
//存储
prop.store(w, null);
w.close();
//继续
GuessGame.start();
} } }

。。。产生随机数并猜测判断的类,不写了

最新文章

  1. beautifulSoup(1)
  2. GitHub 上有哪些完整的 iOS-App 源码值得参考
  3. 1201新课程TSQL语句
  4. 关于Android构建
  5. careercup-树与图 4.7
  6. K相邻算法
  7. 读阮一峰老师 es6 入门笔记 —— 第一章
  8. java并发编程可见性与线程封闭
  9. VS2017 EF本地数据库链接
  10. 【转载】FPGA算法设计随笔
  11. centos7下安装docker(22.docker swarm-----service)
  12. Jupyter Notebook的安装
  13. Maven配置国内镜像仓库
  14. SVG 学习&lt;六&gt; SVG的transform
  15. linux case ${variable} in
  16. sass问题
  17. 发布WebService 1.1
  18. abp项目如何按业务功能模块横向分割?
  19. 【codevs1069】关押罪犯[noip2010](并查集)
  20. java 截取替换掉括号 包括括号中的内容

热门文章

  1. ASP.NET MVC中将控制器分离到类库的实现
  2. 为网站添加ico图标
  3. 微信CRM六大模块的详解
  4. 【读书笔记】iOS-NSString的length
  5. Android源码分析之SparseArray
  6. Python 常用函数time.strftime()简介
  7. Autocomplete:属性介绍、firefox中文支持问题
  8. GridControl控件的数据显示的样式控制(转)
  9. java微信接口之二—获取用户组
  10. 【log4net】配置