设计一个猜数字小游戏,可以试玩5次。试玩结束之后,给出提示:游戏试玩结束,请付费。(要求即使把程序重启也总共只能猜5次)
(Properties: 读取和存文件记录猜数字次数)
代码实现
//记得自己创建个properties文件,里面写好count=6;
import java.io.*;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
public class PropDemo {
public static void main(String[] args) throws IOException {
//读取到properties文件中的键值
Properties prop = new Properties();
FileReader re = new FileReader("test.properties");
prop.load(re);
re.close();
//把读到的键值获取到对应value值
String s = prop.getProperty("count");
//由于properties文件默认键值都是用String,所以需要把value解析成为int
int count = Integer.parseInt(s);
//先判断游戏剩余次数有没有用光
if (count <= 0){
System.out.println("您的游戏剩余次数已用尽,请充值后再使用");
return;
}
System.out.println("欢迎进入游戏,猜数字范围在0-9之间哦");
//创建random对象
Random random = new Random();
//创建扫描器对象
Scanner scanner = new Scanner(System.in);
//如果次数大于0可以继续玩
while (count > 0){
System.out.println("您一共有六次机会,当前剩余 "+count+" 次");
//获取随机数
int i = random.nextInt(10);
int num = -1;
while (num != i){
System.out.println("请输入您猜的数字");
num = scanner.nextInt();
if (num > i){
System.out.println("您猜的数字大了");
}else if (num < i){
System.out.println("您猜的数字小了");
}
}
System.out.println("恭喜您猜中了!!!");
//玩完一次游戏记得把次数减一
count--;
//创建文件写对象
FileWriter writer = new FileWriter("test.properties");
//把变更后的游戏次数写到properties文件中
prop.setProperty("count",String.valueOf(count));
//将表中的属性写入输出流
prop.store(writer,"qiongbibupeiwanyouxi");
writer.close();
if (count <= 0){
System.out.println("您的免费体验次数已用尽,请及时充值!");
break;
}
System.out.println("您是否继续游戏,输入“是”继续进行游戏");
String games = scanner.next();
if (!"是".equals(games)){
System.out.println("ByeBye");
break;
}else {
System.out.println("欢迎您再次游戏");
}
}
}
}