java 将游戏分数保存到文件并确定“高分”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26443957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save game scores to file and determine the "high score"
提问by mrzlaroka
I have written a program that randomly selects a verb in Deutch and asks you for the Perfekt form. It continuously displays new verbs until you make a mistake. Then the program tells you your answer was incorrect and tells you how many points you have earned. The program also writes the number of points into the test.txt file and then re-reads that number from it.
我编写了一个程序,它在 Deutch 中随机选择一个动词并要求您提供 Perfekt 形式。它会不断显示新动词,直到您出错为止。然后程序会告诉您答案不正确,并告诉您获得了多少积分。该程序还将点数写入 test.txt 文件,然后从中重新读取该数字。
Here is the code for my program (it works correctly as described above).
这是我的程序的代码(如上所述它可以正常工作)。
import java.util.Random;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*;
public class Verben{
public static void main(String args[]){
String glagol;
String correct = "Correct!";
String incorrect = "Incorrect!";
int points = 0;
boolean answer;
File file = new File("test.txt");
for(int i = 0; i <= points; i++){
Random random = new Random();
String verben[] = {"trinken", "lesen", "schwimmen", "sterben", "fahren"};
String verbenAnswer[] = {"hat getrunken", "hat gelesen",
"hat geschwommen", "ist gestorben", "ist gefahren"};
glagol = verben[random.nextInt(verben.length)];
System.out.println("Please enter correct form of verb!");
System.out.println(glagol);
String enter = Input.readLine();
if(glagol.equals(verben[0]) && enter.equals(verbenAnswer[0])){
answer = true;
points += 1;
}else if(glagol.equals(verben[1]) && enter.equals(verbenAnswer[1])){
answer = true;
points += 1;
}else if(glagol.equals(verben[2]) && enter.equals(verbenAnswer[2])){
answer = true;
points += 1;
}else if(glagol.equals(verben[3]) && enter.equals(verbenAnswer[3])){
answer = true;
points += 1;
}else if(glagol.equals(verben[4]) && enter.equals(verbenAnswer[4])){
answer = true;
points += 1;
}else{
answer = false;
points += 0;
}
if(answer == true){
System.out.println(correct);
}else{
System.out.println(incorrect);
System.out.println("You collected: " + points + "/" + (i+1));
}
}
try{
PrintWriter output = new PrintWriter(file);
output.println(points);
output.close();
}catch (FileNotFoundException ex){
System.out.printf("ERROR: %s\n", ex);
}
try{
Scanner input = new Scanner(file);
int point = input.nextInt();
System.out.printf("Points: %d\n", point);
}catch(IOException ex){
System.err.println("ERROR");
}
}
}
How can I modify my code to permanently store all attempts in the test.txt file? How can I determine the all-time high score? After each run of the program I would like it to remind me "what is the all-time high score".
如何修改我的代码以将所有尝试永久存储在 test.txt 文件中?如何确定历史最高分?每次运行程序后,我希望它提醒我“历史最高分是多少”。
回答by trooper
One way to do this is...
一种方法是...
Immediately after your for loop, determine the high score by reading your file line-by-line. To keep things simple we will assume that there is one score per line.
在 for 循环之后,立即通过逐行读取文件来确定高分。为简单起见,我们假设每行有一个分数。
// determine the high score
int highScore = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while (line != null) // read the score file line by line
{
try {
int score = Integer.parseInt(line.trim()); // parse each line as an int
if (score > highScore) // and keep track of the largest
{
highScore = score;
}
} catch (NumberFormatException e1) {
// ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR reading scores from file");
}
After determining the high score we can display the appropriate message.
确定高分后,我们可以显示相应的消息。
// display the high score
if (points > highScore)
{
System.out.println("You now have the new high score! The previous high score was " + highScore);
} else if (points == highScore) {
System.out.println("You tied the high score!");
} else {
System.out.println("The all time high score was " + highScore);
}
Finally we append the current score to the end of the file (on its own line).
最后,我们将当前分数附加到文件的末尾(在它自己的行上)。
// append the last score to the end of the file
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
output.newLine();
output.append("" + points);
output.close();
} catch (IOException ex1) {
System.out.printf("ERROR writing score to file: %s\n", ex1);
}
}
回答by Martin
If you want to display the all-time high-score at the beginning of the program then you need to read the file at the beginning of the program. Add all entries in the text-file into an ArrayList(or something similar), then find the greatest element in the list, display this. (Or keep track of the greatest element while reading the file, if you don't need the other scores later).
如果你想在程序开头显示历史最高分,那么你需要在程序开头读取文件。将文本文件中的所有条目添加到一个 ArrayList(或类似的东西)中,然后找到列表中最大的元素,显示它。(或者在阅读文件时跟踪最大的元素,如果您以后不需要其他分数)。
Also when you write a score to the file you need to make sure you add it to the end of the file, not overwriting the file.
此外,当您将乐谱写入文件时,您需要确保将其添加到文件的末尾,而不是覆盖文件。