需求:写程序实现猜数小程序试玩3次,超过三次后如果还要玩要提示:试玩结束,请申请新的试玩资格
分析:
1.写一个游戏类,里面有一个猜数小游戏
2.写一个测试类
A:从文件中读取数据到Properties集合,load,文件已存在,game.txt,数据值:count=0
B:通过Properties集合获取玩游戏的次数
C:判断是否超过三次
是:提示试玩结束,请申请新的试玩资格
否:可以继续玩,次数加一,重写回文件,store方法
游戏类
public class Game {
private Game(){}
public static void play(){
//生成一个随机数
Random r=new Random();
int num = r.nextInt(100)+1;
while (true){
Scanner sc=new Scanner(System.in);
System.out.println("请输入你猜的数字");
int i=sc.nextInt();
if (i>100||i<0){
System.out.println("输入的数字不在范围内,请重新输入");
i=sc.nextInt();
}
if (i>num){
System.out.println("你猜的大的");
}else if (i<num){
System.out.println("你猜的小了");
}else{
System.out.println("猜对了");
break;
}
}
}
}
测试类
public class GameDemo {
public static void main(String[] args)throws IOException {
//从文件中读取数据到Properties集合,load,文件已存在,abc.txt,数据值:count=0
Properties pt=new Properties();
FileReader fr=new FileReader("E:\\abc.txt");
pt.load(fr);
fr.close();
//:通过Properties集合获取玩游戏的次数
String count = pt.getProperty("count");
//判断是否超过三次
int i = Integer.parseInt(count);
if (i>3){
System.out.println("提示试玩结束,请申请新的试玩资格");
}else{
Game.play();
i++;
pt.setProperty("count",String.valueOf(i));
FileWriter fw=new FileWriter("E:\\abc.txt");
pt.store(fw,null);
fw.close();
}
}
}
浙公网安备 33010602011771号