【日常练习】一个可以试玩五次的猜数小游戏

练习要求:
请设计一个猜数字小游戏,可以试玩5次。试玩结束之后,给出提示:游戏试玩结束,请付费。

小游戏代码

import java.util.Scanner;

public class GuessNum {

    public static void startGame() {
        int targetNum = (int) (Math.random() * 100);
        int count = 0;
        while (true) {
            System.out.println("请输入一个数字(0~99)");
            Scanner sc = new Scanner(System.in);
            int guessNum = sc.nextInt();
            count++;
            if (guessNum > targetNum) {
                System.out.println("猜大了,您已经猜了" + count + "次");
            }else if (guessNum < targetNum) {
                System.out.println("猜小了,您已经猜了" + count + "次");
            } else {
                System.out.println("恭喜您猜中了,您猜了" + count + "次");
                break;
            }
        }
    }
}

限定只能试玩五次

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class HomeWork01 {
    public static void main(String[] args) throws IOException {
        //创建文件
        File file = new File("d:\\test\\game.txt");
        if (!file.exists()) file.createNewFile();

        //读取游戏次数
        Properties properties = new Properties();
        FileReader reader = new FileReader(file);
        properties.load(reader);
        reader.close();

        //将读取的字符串转化为int类型
        String count = properties.getProperty("count");
        int num = Integer.parseInt(count);
        if (count == null) num = 0;

        //判断是否已经试玩了五次
        if (num > 5){
            System.out.println("游戏试玩结束,请付费。");
            System.exit(0);
        }else {
            //写入新游戏次数
            properties.setProperty("count", String.valueOf(++num));
            FileWriter writer = new FileWriter(file);
            properties.store(writer, "GuessNumberGame");
            writer.close();
            //启动游戏
            GuessNum.startGame();
        }
    }
}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值