Я хотел добавить способ хранения очков, заработанных между играми (Java) - PullRequest
0 голосов
/ 15 сентября 2018

У меня было несколько попыток использовать java.io несколькими способами, но я так и не смог заставить его работать. Моя идея состояла в том, чтобы сохранить очки, заработанные в файле с именем save_data.txt, затем извлечь 3 старших целых числа из этого списка и отобразить их в списке лидеров.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class TextFind {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<Integer>();
File file = new File("save_data.txt");
BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;

    while((text = reader.readLine()) != null) {
        list.add(Integer.parseInt(text));
    }
}catch (FileNotFoundException e) {
    e.printStackTrace();
}catch (IOException e) {
    e.printStackTrace();

} finally {
    try {
        if(reader != null) {
            reader.close();
        }
    }catch(IOException e) {     
    }
}

}
}

Я взял это и позвонил, когда игра перестала работать. Кажется, ничего не делать.

1 Ответ

0 голосов
/ 16 сентября 2018

Вы не так уж далеко на самом деле. Есть ли значения в вашем файле save_date.txt? Вот пример использования Java 8:

public static void main(String[] args) {
    List<Integer> highScore = Arrays.asList(1, 2); // Dummy values
    Path filePath = Paths.get("save_data.txt"); // Your saved data

    // Transform available high scores to a single String using the System line separator to separated the values and afterwards transform the String to bytes ...
    byte[] bytes = highScore.stream().map(Object::toString).collect(Collectors.joining(System.lineSeparator())).getBytes();

    try {
        // Write those high score bytes to a file ...
        Files.write(filePath, bytes, StandardOpenOption.CREATE);
    } catch (IOException e) {
        e.printStackTrace();
    }

    List<String> lines = Collections.emptyList();
    try {
        // Read all available high scores lines from the file ...
        lines = Files.readAllLines(filePath);
    } catch (IOException e) {
        e.printStackTrace();
    }
    int skipLines = Math.max(lines.size() - 3, 0); // You only want the three highest values so we use the line count to determine the amount of values that may be skipped and we make sure that the value may not be negative...

    // Stream through all available lines stored in the file, transform the String objects to Integer objects,  sort them, skip all values except the last three and sort their order descending
    highScore = lines.stream().map(Integer::valueOf).sorted().skip(skipLines).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    // Print the result
    highScore.forEach(System.out::println);
}
...