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

2012/5/23

How do I store a variable to a text file

TechWebLock TechWebLock

2012/5/23

#
Basically I want to store the top 3 scores from 3 levels to a text file and then retrieve them when the user opens the high score actor. I have tried all different coding but I have had no luck. Any ideas for a simple system. I was thinking using an IF statment that would check the level then check the current high scores and if it was higher overwrite the line in the file with the new score. Thanks :)
trash1000 trash1000

2012/5/23

#
Why don't you retrieve all the scores and save them back into instance variables when you start the game. Now a level ends and you check for the score to be higher than the one you just retrieved. If so you change the score and write it back into the file. Like you retrieve the scores into 3 instance variables - score1, score2 and score3 for example. Now the player beats level 1 - you check his score to be higher than score1, if so you set score1 to the player's score and write it to the file (the other levels go accordingly). Here are a few methods with which you can easily write variables to a file, read them out again and store them in instance variables:
    private int a, b, c;
    public void setScores(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
    
    public void writeScores() {
        try {
            BufferedWriter output = new BufferedWriter(new FileWriter("scores.txt"));
            output.flush();
            output.write(""+a);
            output.newLine();
            output.write(""+b);
            output.newLine();
            output.write(""+c);
            output.newLine();
            output.close();
        }
        catch(Exception e) { }
    }  
    
    public void readScores() {
        try {
            URL path = getClass().getClassLoader().getResource("scores.txt");
            InputStream stream = path.openStream();
            BufferedReader input = new BufferedReader(new InputStreamReader(stream));
            a = Integer.parseInt(input.readLine());
            b = Integer.parseInt(input.readLine());
            c = Integer.parseInt(input.readLine());
            input.close();
            System.out.println(a);
            System.out.println(b);
            System.out.println(c);
        }
        catch(Exception e) { }
    }
You need to login to post a reply.