有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jpanel我想添加一种在游戏之间存储积分的方法(Java)

我曾多次尝试使用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) 个答案

  1. # 1 楼答案

    事实上,你离得并不远。保存日期中是否有值。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);
    }