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
游戏结果