练习要求:
请设计一个猜数字小游戏,可以试玩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();
}
}
}