首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我想添加一种方法来存储两场比赛之间获得的点数(Java)

我想添加一种方法来存储两场比赛之间获得的点数(Java)
EN

Stack Overflow用户
提问于 2018-09-16 04:13:01
回答 1查看 124关注 0票数 -1

我曾多次尝试以多种方式使用java.io,但始终无法使其正常工作。我的想法是将获得的点数存储在一个名为save_data.txt的文件中,然后检索该列表中的3个最高整数,并将它们显示在排行榜上。

代码语言:javascript
复制
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) {     
    }
}

}
}

当游戏停止运行时,我调用了它。它似乎什么也做不了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-16 05:35:22

实际上,你离得并不远。您的save_date.txt文件中是否有值?下面是一些使用Java 8的示例:

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52348474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档