- package cn.itheima.NumberGame;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.Reader;
- import java.io.Writer;
- import java.util.Properties;
- import java.util.Scanner;
- /*
- * 需求:猜数字小游戏,当游戏次数达5次以上时,提示请付费,并且进行异常处理。
- */
- public class guessNumberGame {
- public static void main(String[] args) {
- // 把数据加载到集合中
- Properties prop = new Properties();
- // 创建输入流,并且进行异常处理
- Reader r = null;
- try {
- r = new FileReader("count.txt");
- prop.load(r);
- } catch (IOException e) {
- System.out.println("玩游戏失败!");
- } finally {
- if (r != null) {
- try {
- r.close();
- } catch (IOException e) {
- System.out.println("玩游戏失败!");
- }
- }
- }
- // 根据键值获取数据
- String value = prop.getProperty("count");
- int number = Integer.parseInt(value);
- // 判断
- if (number > 5) {
- System.out.println("试玩结束,请进行付费!");
- System.exit(0);
- } else {
- // 游戏次数 ++
- number++;
- // 创建输出流,并且进行异常处理
- Writer w = null;
- try {
- prop.setProperty("count", String.valueOf(number));
- w = new FileWriter("count.txt");
- prop.store(w, null);
- } catch (IOException e) {
- System.out.println("游戏失败了!");
- } finally {
- if (r != null) {
- try {
- r.close();
- } catch (IOException e) {
- System.out.println("游戏失败!");
- }
- }
- gameStart();
- }
- }
- }
- public static void gameStart() {
- // 产生一个随机数
- int number = (int) (Math.random() * 100) + 1;
- // 定义一个统计变量
- int count = 0;
- while (true) {
- // 键盘录入一个数据
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入数据(1-100):");
- int guessNumber = sc.nextInt();
- count++;
- // 判断
- if (guessNumber > number) {
- System.out.println("你猜的数据" + guessNumber + "大了");
- } else if (guessNumber < number) {
- System.out.println("你猜的数据" + guessNumber + "小了");
- } else {
- System.out.println("恭喜你," + count + "次就猜中了");
- break;
- }
- }
- }
- }
复制代码
|