需求:编写一个猜数字的小游戏,只能试玩三次,玩完之后如果还想玩则要提示:游戏已经玩完,想玩请充值。
思路:1.定义猜数字游戏的类
代码如下
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public GuessNumber() {
}
public static void start()
{
Random r=new Random();
int i = r.nextInt(100) + 1;
System.out.println("游戏开始请输入你要猜的数字");
while(true) {
Scanner sc = new Scanner(System.in);
int i1 = sc.nextInt();
if (i1 > i) {
System.out.println("你猜的数字" + i1 + "大了");
} else if (i1 < i) {
System.out.println("你猜的数字" + i1 + "小了");
} else {
System.out.println("恭喜你猜对了");
break;
}
}
}
}
2.定义一个测试类:测试类中有main方法:
A.定义文件game.txt文件中有数据count=0;
从文件中读取数据到Properties集合中,用load()方法实现。
B.通过Properties中获取文件次数:此时的文件次数为字符串,要用Integer.parseInt转换
用int类型接受。
C.判断次数是否达到三次?
1.如果达到则给出提示,游戏试玩已经结束,想玩请充值
2.若没有达到,则继续调用玩游戏方法,玩游戏次数number+1,存储到Properties集合中,用Properties的store()方法重新把新数据写入文件中。
代码如下:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class Properties_Dome {
public static void main(String[] args) throws IOException {
Properties prop=new Properties();
FileReader fr=new FileReader("E:\Practice_3\itheima002");
prop.load(fr);
fr.close();
String count = prop.getProperty("count");
int number = Integer.parseInt(count);
if(number>=3)
{
System.out.println("你的试玩次数已经结束请到www.itcast.com处充值");
} else {
GuessNumber.start();
number++;
prop.setProperty("count",String.valueOf(number));
FileWriter fw=new FileWriter("E:\Practice_3\itheima002");
prop.store(fw,null);
fw.close();
}
}
}



