利用Properties类中方法控制猜数字游戏游玩次数

Properties类是用来读取配置文件中的key与value值的类

其中常用方法:

1.stringPropertyName():读取文件中的key信息,并返回存有key的集合。

2.getProperty(String key):通过key获取vlaue值

3.load(InputStream 字节输出流):读取文件中的键值对

4.setProperty(String key,String value):设置字符串类型的key与value值

5.store(OutputStream 字节输入流,String 说明): 将键值对写入到文件中,后面的参数是用来说明写入的文件是干什么的。

下面看实现代码

public class Guessnum {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		// TODO Auto-generated method stub
		Properties p = new Properties();
		p.load(new FileInputStream("abc/b.txt"));
		Set<String> counts = p.stringPropertyNames();
		//通过迭代器对象获取key对应的value值
		Iterator<String> it = counts.iterator();
		int count = Integer.parseInt(p.getProperty(it.next()));
		
        if(count!=0){
			System.out.println("猜数字游戏");
			  Random ran = new Random();
	           int x = ran.nextInt(100);
			while(true){
	        Scanner scn = new Scanner(System.in);
	        System.out.print("请输入一个1-100之间的整数:");
	        int num = scn.nextInt();
	       
			// System.out.println(num);
	        if(num<0||num>100){
	        	System.out.println("你输入的数不在0~100之间");
	        	continue;
	        }
	        else if(num>x){
	            System.out.println("大了!!");	
	        }
	        else if(num<x){
	            System.out.println("小了!!");
	        }
	        else{
	        	System.out.println("恭喜你,猜对了!!!");
	        	break;
	        }
	        }
			//剩余游戏次数减1
			count--;
			System.out.println("剩余游戏次数:" + count);
			p.setProperty("count", String.valueOf(count));
	        p.store(new FileOutputStream("abc/b.txt"),"记录剩余游戏次数");
		}else{
			System.out.println("少年充Q币吗?");
		}
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值