【Java】实现只能玩3次的猜数小游戏
game.txt
count=0
GameNumber.java
package LearnJava15;
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
private GuessNumber() {
}
public static void start() {
Random r = new Random();
int number = r.nextInt(100) + 1;
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要猜的数字:");
int guessNumber = sc.nextInt();
if (guessNumber > number) {
System.out.println("猜大了!");
} else if ((guessNumber < number)) {
System.out.println("猜小了!");
} else {
System.out.println("猜中了!");
break;
}
}
}
}
PorepertiesTest.java
package LearnJava15;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PorepertiesTest {
public static void main(String[] args) throws IOException {
// 从文件中读取数据到集合中
Properties prop = new Properties();
FileReader fr = new FileReader("D:\\MyProject\\Java\\Demo2\\src\\LearnJava15\\game.txt");
prop.load(fr);
fr.close();
// 通过集合获取到玩游戏的方法
String count = prop.getProperty("count");
int number = Integer.parseInt(count);
if (number >= 3) {
System.out.println("游戏已结束,想玩请充钱!");
} else {
// 玩游戏
GuessNumber.start();
// 次数+1,重新写入文件
number++;
prop.setProperty("count", String.valueOf(number));
FileWriter fw = new FileWriter("D:\\MyProject\\Java\\Demo2\\src\\LearnJava15\\game.txt");
prop.store(fw, null);
fw.close();
}
}
}
效果
请输入你要猜的数字:
70
猜小了!
请输入你要猜的数字:
100
猜大了!
请输入你要猜的数字:
85
猜小了!
99
猜中了!
本文来自博客园,作者:木子欢儿,转载请注明原文链接:https://www.cnblogs.com/HGNET/p/16200438.html