This site requires JavaScript, please enable it in your browser!
Greenfoot back
mitrolex
mitrolex wrote ...

2017/2/28

Working with files

mitrolex mitrolex

2017/2/28

#
Hello guys, it's me again with the Flappy Bird game. I'd like to make a 'best score' method that is saved in a txt file that i've created. And i need it to always show the best score on the death screen. Here's what i managed to do (steal) so far:
BufferedWriter file = null;
        try 
        {
            file = new BufferedWriter(new FileWriter("score.txt"));            
            file.write(""+score);
            file.close();
        }
        catch (IOException ioe) 
        {
            ioe.printStackTrace();
        }
        finally
        {
            try {
                file.close();
            }
            catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
It just saves the last score to the txt file.
danpost danpost

2017/2/28

#
That is what the code you have acquired does -- it saves the current score to the file. If you want it to only save the current score when it is the best score, then you need to compare the two to determine if the current score is indeed the best one. This means you need to read from the file first; then, compare; then write the current score if better. After that, you can display the true best score. Time to steal some more code. Save the above code for when the current score IS better.
Super_Hippo Super_Hippo

2017/2/28

#
If you don't want to steal more code which you (probably) can't understand, try to use the UserInfo class which can create an .csv file and read from it without complicated code.
mitrolex mitrolex

2017/2/28

#
Thank's guys. Danpost, i understand what you are saying but my biggest problem is reading the file.
danpost danpost

2017/2/28

#
It is almost the same except with readers instead of writers:
String line = null;
BufferedReader br = null;
try
{
    br = new BufferedReader(new FileReader("score.txt"));
    line = br.readLine();
    br.close();
}
catch(Exception e)
{
    System.out.println(e);
    try { br.close(); } catch (Exception x){}
    line = "0";
}
if (score > Integer.parseInt(line))
{
    // etc.
mitrolex mitrolex

2017/3/8

#
Thanks danpost, it worked.
You need to login to post a reply.