这是一段猜数字的游戏代码。同项目文件夹下有个game.txt文件内容只有“count=3(次数)”,在其他代码功能测试全部通过的情况下唯独加入数据流以后就开始获取不到值。
import java.io.*; import java.util.Properties; import java.util.Random; import java.util.Scanner; <em>/** * </em><strong><em>@Author </em></strong><em>Diuut * </em><strong><em>@Date </em></strong><em>2019/7/24 16:23 */ </em>public class GuessGame { public static void main(String[] args) throws IOException { Properties prop = new Properties(); BufferedReader bis = new BufferedReader(new FileReader("Week04\\game.txt")); BufferedWriter bos = new BufferedWriter(new FileWriter("Week04\\game.txt")); prop.load(bis); int count = Integer.<em>parseInt</em>(prop.getProperty("count")); Scanner sc = new Scanner(System.<em>in</em>); int choose = 1; while (choose == 1 && count > 0) { <em>Game</em>(); count--; String ct = count + ""; prop.setProperty("count", ct); prop.store(bos, null); System.<em>out</em>.println("是否再玩一次?输入1继续,输入其他退出"); choose = sc.nextInt(); if (choose != 1) { bis.close(); bos.close(); break; } } if (choose == 1 && count == 0) System.<em>out</em>.println("剩余次数为0,请上diuut.xyz充值"); prop.setProperty("count", prop.getProperty("count")); prop.store(bos, null); bis.close(); bos.close(); } public static void Game() { Random rd = new Random(); int num = rd.nextInt(100) + 1; Scanner sc = new Scanner(System.<em>in</em>); System.<em>out</em>.println("请输入1-100之间的一个整数:"); int inNum = sc.nextInt(); while (num != inNum) { if (inNum > 0 && inNum < num) { System.<em>out</em>.println("您输入的数字小了,请重新输入:"); inNum = sc.nextInt(); } else if (inNum < 101 && inNum > num) { System.<em>out</em>.println("您输入的数字大了,请重新输入:"); inNum = sc.nextInt(); } else { System.<em>out</em>.println("您输入的数字不在100范围之内,请重新输入:"); inNum = sc.nextInt(); } } System.<em>out</em>.println("恭喜您猜对了,数字为" + num); } }
原因结果是因为 创建BufferedWriter对象时直接把文件清空重置了,导致后面properties读不到数据,这里了只需要把BufferedWriter对象放到load方法读取数据之后再创建就可以正常使用了。
BufferedReader bis = new BufferedReader(new FileReader("Week04\\game.txt")); prop.load(bis); BufferedWriter bos = new BufferedWriter(new FileWriter("Week04\\game.txt"));