在我的代码中玩游戏,但首先读取文件并将排行榜保存在链接列表中。玩完游戏后,得到一个分数,并将这个分数按照链表的顺序添加进去。我所要做的就是将这个新列表写入 txt 文件。
这是玩游戏之前的列表。
佩林;30
卡恩;15
阿里;50
耶利兹;25
厘米;40
可以;35
欧洲经委会;5
西贝尔;30
雷姆兹;20
纳赞;10
这是我的链表节点类:
public class Node {
private Object data;
private Node link;
public Node(Object dataToAdd) {
data = dataToAdd;
link = null;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
}
这是我的 SLL 类(class):
public class SingleLinkedList {
Node head;
public void insertScore(Object dataToAdd) {
Node newNode = new Node(dataToAdd);
if (head == null) {
head = newNode;
} else {
int score = getScore(dataToAdd);
int headObjectScore = getScore(head.getData());
if (score > headObjectScore) {
Node temp = head;
head = newNode;
newNode.setLink(temp);
} else {
Node currentNode = head;
// to handle if the newNode has the biggest score
if (currentNode.getLink() == null) {
currentNode.setLink(newNode);
currentNode = newNode;
}
while (currentNode.getLink() != null) {
Node oldNode = currentNode;
currentNode = currentNode.getLink();
if (score > getScore(currentNode.getData())) {
oldNode.setLink(newNode);
newNode.setLink(currentNode);
break;
}
// to handle if the newNode has the biggest score
if (currentNode.getLink() == null) {
currentNode.setLink(newNode);
currentNode = newNode;
}
}
}
}
}
private int getScore(Object data) {
return Integer.valueOf(((String) data).split(";")[1]);
}
我已经完成了管理高分表,但不知道如何使用新的链接列表更改 .txt 文件
最佳答案
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
对于 Java 7+,您可以使用这种方式。下面的链接列出了几种在 Java 中创建文件并打印文件的方法。考虑一下您要写多少内容以及是否需要:
- 附加到现有文件
- 位于新文件中并删除旧内容
- 位于全新文件中
关于java - Java中编辑打开的.txt中的文件并替换为新数据的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62346062/