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

2017/1/24

File i/o to Display top 5 scores when button is clicked

1
2
new_on_greenfoot new_on_greenfoot

2017/1/24

#
I am creating the game Snake and I would like it so that when I click on the high scores button you are able to see the top five scores. In order for this to happen I need the game to be able to save every score permanently and then display the top 5. I am told I have to use File i/o to create this. Please help! Here is the code I have so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.io.*;
import java.util.ArrayList;
/**
 * Write a description of class HighScoresButton here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class HighScoresButton extends Actor
{
    ArrayList<String> highScores = new ArrayList();
    /**
     * Act - do whatever the HighScoresButton wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        if (Greenfoot.mouseClicked(this))
        {
            Greenfoot.setWorld(new HighScores());
         
            try
            {
                createFile();
                readFile();
            }
            catch(IOException e)
            {
                System.err.println("Caught IOException: " + e.getMessage());
            }
        }
        }
    public void createFile() throws IOException
    {
        FileWriter fw = new FileWriter("High Scores.txt", true);
        String highscore = Integer.toString(GameOver.finalScore.getValue());
        for (int x=0; x < highscore.length(); x++)
        {
            fw.write(highscore.charAt(x));
        }
        fw.close();
    }
    public void readFile() throws IOException
    {
        FileReader fr = new FileReader("High Scores.txt");
        char [] a = new char [50];
        fr.read(a);
        for (char c : a)
        {
            System.out.print(c);
        }
        fr.close();
    }
    }   
danpost danpost

2017/1/24

#
Before going into specifics on this, I want to make sure you want to proceed in this direction (using i/o). If, you include file writing in your project, the file writing will only work on a local network. I will not work on the greenfoot site or on a web page. Is this still what you want?
new_on_greenfoot new_on_greenfoot

2017/1/24

#
Yes it is. I was tweaking with my code last night and was able to have the scores appear on the screen when I click the button but I am not able to get the scores written in to my file. Here is my recent code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.io.*;
import java.util.ArrayList;
/**
 * Write a description of class HighScoresButton here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class HighScoresButton extends Actor
{
    ArrayList<String> highScores = new ArrayList();
    public int scoreCounter = 0;
    /**
     * Act - do whatever the HighScoresButton wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        if (Greenfoot.mouseClicked(this))
        {
            Greenfoot.setWorld(new HighScores());
 
            try
            {
                writeFile();
                readFile();
            }
            catch(IOException e)
            {
                System.err.println("Caught IOException: " + e.getMessage());
            }
        }
    }
 
    public void writeFile()
    {
        FileWriter fw = new FileWriter("High Scores.txt", true);
        String highscore = Integer.toString(GameOver.finalScore.getValue());
        for (int x=0; x < highscore.length(); x++)
        {
            fw.write(highscore.charAt(x));
        }
        fw.close();
    }
 
    public void readFile() throws IOException
    {
        FileReader fr = new FileReader("High Scores.txt");
        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();
        while (line != null)
        {
            //System.out.print(c);
            if (scoreCounter == 0)
            {
                HighScores.highScore.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 1 && line !=null)
            {
                HighScores.highScore2.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 2 && line !=null)
            {
                HighScores.highScore3.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 3 && line !=null)
            {
                HighScores.highScore4.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 4 && line !=null)
            {
                HighScores.highScore5.setValue(new Integer(line));
                line = br.readLine();
            }
        }
        br.close();
        fr.close();
    }
}   
danpost danpost

2017/1/24

#
Try wrapping your FileWriter object in a BufferedWriter object and outputting the character string in one command (instead of each character individually).
new_on_greenfoot new_on_greenfoot

2017/1/24

#
I understand how to wrap the BufferedWriter object around the FileWriter object but I'm not quite sure I get what you mean when you say to output the character string in one command
danpost danpost

2017/1/24

#
new_on_greenfoot wrote...
I understand how to wrap the BufferedWriter object around the FileWriter object but I'm not quite sure I get what you mean when you say to output the character string in one command
I was just giving two possible options to try (1) using a BufferedWriter wrapper; and (2) outputting the string in one command -- like so:
1
fw.write(highscore);
instead of lines 40 through 43.
new_on_greenfoot new_on_greenfoot

2017/1/25

#
I apologize as I am fairly new to coding. This is my recent code. It is writing my score but it writes it on the same line. Each score has to be written on a new line. How would I go about doing that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.io.*;
import java.util.ArrayList;
/**
 * Write a description of class HighScoresButton here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class HighScoresButton extends Actor
{
    ArrayList<String> highScores = new ArrayList();
    public int scoreCounter = 0;
    /**
     * Act - do whatever the HighScoresButton wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        if (Greenfoot.mouseClicked(this))
        {
            Greenfoot.setWorld(new HighScores());
 
            try
            {
                writeFile();
                readFile();
            }
            catch(IOException e)
            {
                System.err.println("Caught IOException: " + e.getMessage());
            }
        }
    }
 
    public void writeFile() throws IOException
    {
        FileWriter fw = new FileWriter("High Scores.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        String highscore = Integer.toString(GameOver.finalScore.getValue());
        for (int x=0; x < highscore.length(); x++)
        {
            fw.write(highscore.charAt(x));
        }
        //fw.write(highscore);
        bw.close();
        fw.close();
         
    }
 
    public void readFile() throws IOException
    {
        FileReader fr = new FileReader("High Scores.txt");
        BufferedReader br = new BufferedReader(fr);
        String line = br.readLine();
        while (line != null)
        {
            //System.out.print(c);
            if (scoreCounter == 0)
            {
                HighScores.highScore.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 1 && line !=null)
            {
                HighScores.highScore2.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 2 && line !=null)
            {
                HighScores.highScore3.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 3 && line !=null)
            {
                HighScores.highScore4.setValue(new Integer(line));
                line = br.readLine();
                scoreCounter++;
            }
            if (scoreCounter == 4 && line !=null)
            {
                HighScores.highScore5.setValue(new Integer(line));
                line = br.readLine();
            }
        }
        br.close();
        fr.close();
    }
}   
new_on_greenfoot new_on_greenfoot

2017/1/25

#
I also seem to get an error that reads: java.lang.NumberFormatException: For input string: "140030300010" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:583) at java.lang.Integer.<init>(Integer.java:867) at HighScoresButton.readFile(HighScoresButton.java:67) at HighScoresButton.act(HighScoresButton.java:27) at greenfoot.core.Simulation.actActor(Simulation.java:604) at greenfoot.core.Simulation.runOneLoop(Simulation.java:562) at greenfoot.core.Simulation.runContent(Simulation.java:221) at greenfoot.core.Simulation.run(Simulation.java:211) when I click on my high scores button
danpost danpost

2017/1/25

#
Okay. try this one:
1
fw.write(highscore+"\n");
new_on_greenfoot new_on_greenfoot

2017/1/25

#
I replaced your line of code in for the for loop I have. I assumed that is what you meant for me to do. It still seems to be writing the score on the same line.
danpost danpost

2017/1/25

#
new_on_greenfoot wrote...
I replaced your line of code in for the for loop I have. I assumed that is what you meant for me to do. It still seems to be writing the score on the same line.
From your last code post, that line should be your uncommented line 45 and lines 41 through 44 should be commented out or removed.
new_on_greenfoot new_on_greenfoot

2017/1/25

#
Yes that is what I have done
danpost danpost

2017/1/25

#
Change the second parameter in the FileWriter constructor call to 'false' once (line 38) so that all erroneous output is replaced. Then, change it back to 'true'. Also, instead of this:
1
fw.write(highscore+"\n");
you could do this:
1
2
fw.write(highscore);
fw.newLine();
new_on_greenfoot new_on_greenfoot

2017/1/25

#
I'm not quite sure what you mean when you say to set it back to true. Could you please give me an example? Also newLine() is an error because it cannot find the symbol
danpost danpost

2017/1/25

#
new_on_greenfoot wrote...
I'm not quite sure what you mean when you say to set it back to true. Could you please give me an example?
I meant that you change 'true' on line 38 to 'false'; compile and run to write one high score; then undo the edit (change the 'false' back to 'true'). The problem is that the first line of your high scores file is corrupted (due to writing scores without line breaks) and we need to start with a fresh file.
There are more replies on the next page.
1
2