简体   繁体   English

在Java中使用文件io创建一个高分

[英]creating a highscore with file io in Java

I have been attempting to create a highscore with file.io but have not been able to do it. 我一直在尝试使用file.io创建一个高分,但一直无法做到。 This is the code I have. 这是我的代码。

public void highScore ()
{
    int highScore = 0;
    String line = "";
    try
    {
        BufferedReader reader = new BufferedReader (new FileReader ("highScores"));
        while ((line = reader.readLine ()) != null)                 // read the score file line by line
        {
            try
            {
                int score = Integer.parseInt (line); // 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");
    }
    c.println (highScore);
}

My text file has only numbers in it in each line 我的文本文件每一行中只有数字

I guess you get: 我想你会得到:

"ERROR reading scores from file" “读取文件中的分数时出错”

You should fix your filename extension: 您应该修复文件扩展名:

BufferedReader reader = new BufferedReader (new FileReader ("highScores.txt"));

and make sure the file lies in the project's folder. 并确保文件位于项目的文件夹中。

Also, notice you read two lines from the file each time, at the end of the while loop and in the while header, so delete line = reader.readLine (); 另外,请注意,您每次都在while循环的末尾和while标题中从文件中读取了两行,因此请删除line = reader.readLine (); at the end of the loop. 在循环的末尾。

As a side note the best practice would be catching Exception . 附带说明一下,最佳实践是捕获Exception Right now you are just trying to catch IOException , do something like 现在,您只是想捕获IOException ,执行类似

catch(Exception e){
   e.printStackTrace();
}

As Exception is super class of all exceptions you can see if the code is breaking because of some other exception (in this case it might be FileNotFoundException ) 由于Exception是所有异常的超类,因此您可以查看代码是否由于其他异常而中断(在这种情况下,它可能是FileNotFoundException

and printing the stack tarce will help you point out the issue with line number in the code where exactly you are getting an exception. 并打印堆栈的tarce可以帮助您指出代码中确切存在异常的行号问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM