1 package day10.lesson3;
2
3 import java.io.FileReader;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.util.Properties;
7
8 /*
9 3.4 案例-Properties实现猜数字游戏
10
11 实现猜数字小游戏只能试玩3次,如果还想玩,提示:游戏试玩已结束,想玩请充值
12 */
13 public class PropertiesTest {
14 public static void main(String[] args) throws IOException {
15 Properties prop = new Properties();
16 FileReader fr = new FileReader("stage2\\src\\day10\\lesson3\\game.txt");
17
18 prop.load(fr);
19 fr.close();
20
21 String countStr = prop.getProperty("count");
22 int count = Integer.parseInt(countStr);
23
24 if(count >= 3){
25 System.out.println("游戏试玩已结束,想玩请充值");
26 }else {
27 GuessNumber.start();
28 count++;
29 prop.setProperty("count", String.valueOf(count)); //int转str
30 FileWriter fw = new FileWriter("stage2\\src\\day10\\lesson3\\game.txt");
31 prop.store(fw, null);
32 fw.close();
33 }
34
35 //运行三次后,输出:游戏试玩已结束,想玩请充值
36 }
37 }
1 package day10.lesson3;
2
3 import java.util.Random;
4 import java.util.Scanner;
5
6 public class GuessNumber {
7
8 public GuessNumber() {
9 }
10
11 public static void start(){
12 Random r = new Random();
13 int number = r.nextInt(100) + 1; //1-100
14
15 while (true){
16 Scanner sc = new Scanner(System.in);
17 System.out.println("请输入你猜的数字:");
18 int guessNum = sc.nextInt();
19
20 if(guessNum > number){
21 System.out.println(guessNum + "猜大了");
22 }else if (guessNum < number){
23 System.out.println(guessNum + "猜小了");
24 }else {
25 System.out.println("恭喜,猜中啦");
26 break;
27 }
28 }
29 }
30
31 }
#Tue Jun 08 17:39:52 CST 2021
count=3