当前位置:网站首页>Guessing game (read data from file)

Guessing game (read data from file)

2022-07-07 23:07:00 Anny Linlin

Guess the game : There are three chances to guess numbers , If you use up three opportunities, you need to recharge the website . If you haven't used up three chances, you can continue to play . The number of games played is stored in the file .
Ideas :( To be added )

import java.util.Random;
import java.util.Scanner;

public class GuessNumber {
    

	public GuessNumber() {
    

	}

	static void guess() {
    

		Random r = new Random();
		int rNum = r.nextInt(100);

		while (true) {
    
			System.out.println(" Please enter an integer :");
			Scanner scan = new Scanner(System.in);

			int num = scan.nextInt();
			scan.nextLine();

			if (num < rNum) {
    

				System.out.println(" Guess a little !");

			} else if (num > rNum) {
    

				System.out.println(" Guess the !");
			} else {
    
				System.out.println(" You guessed it !");
				break;
			}

		}
	}
}

```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Properties;

public class Test {

	public static void main(String[] args) throws IOException {
		//  Read data from file to properties Collection , use load Method realization 
		Properties p = new Properties();
		FileReader fr = new FileReader("count.txt");
		p.load(fr);
		fr.close();

		//  adopt properties Collection to get data 
		String s = p.getProperty("count");
		int count = Integer.parseInt(s);
		System.out.println(count);

		if (count >= 3) {
			System.out.println(" You have used up 3 Second chance !");
		} else {
			GuessNumber.guess();
			count++;
		}

		//  take count write file 
		FileWriter fw = new FileWriter("count.txt");
		Properties pw = new Properties();

		pw.setProperty("count", String.valueOf(count));
		pw.store(fw, null);
		fw.close();

	}

}

原网站

版权声明
本文为[Anny Linlin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130601098146.html