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

2013/12/8

File I/O and newLine, Help!

Adept_Red Adept_Red

2013/12/8

#
So I'm trying my hand at some basic file i/o following a few online tutorials and such. I think I have the right idea but there is a multitude of ways to accomplish this, and varying examples are starting to make my head spin. My code definitely could use some help... Ironically, the reason I cannot compile currently actually due to newLine() not being recognizable. I ran into this problem using \n in a drawString before, but this is not as easy to work around. Here is my code for the I/O. If it would be more helpful to post the entire class I will do so, but it is lengthy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static int[] loadScores() throws IOException
    {
        //load preiviously saved scores from file
        BufferedReader inputStream = null;
        int scoreArray[] = new int[5];
         
        inputStream = new BufferedReader(new FileReader("highscores.txt"));
        int num = 0; //line count
        String t = "";
        int start = Integer.parseInt(inputStream.readLine()); //first number in file
        while((t = inputStream.readLine()) != null) // only if there is something to read
        {
            scoreArray[num] = Integer.parseInt(t);
            num++;
        }
        inputStream.close();
 
        return scoreArray;
    }
1
2
3
4
5
6
7
8
9
10
11
//save new array of highscores to file
        FileWriter outputStream = null;
         
        outputStream = new FileWriter("highscores.txt", false);
        for (int k=0; k < allArray.length; k++)
        {
            outputStream.write(allArray[k]);
            outputStream.newLine();
        }
        outputStream.close();
       }
danpost danpost

2013/12/8

#
'newLine' is a method of the BufferedWriter class (not the FileWriter class). You need to wrap a BufferedWriter around the FileWriter.
Adept_Red Adept_Red

2013/12/8

#
Ah ha! You are correct good sir. Not sure how I missed that when just did it in input...oh well. Along with that I have added the try/catch and exceptions, it is giving me an error in the act() method where I have declared...
1
int []previousScores = loadScores();
the error being...
unreported exception, must be caught or declared to be thrown.
It would seem I have done that though, no? Is there something that needs to be added to the declaration of loadScores in act()? Here is the current 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
public static int[] loadScores() throws Exception
    {
        //load preiviously saved scores from file
        BufferedReader inputStream = null;
        int scoreArray[] = new int[5];
         
        try
        {
            inputStream = new BufferedReader(new FileReader("highscores.txt"));
            int num = 0; //line count
            String t = "";
            int start = Integer.parseInt(inputStream.readLine()); //first number in file
            while((t = inputStream.readLine()) != null) // only if there is something to read
            {
                scoreArray[num] = Integer.parseInt(t);
                num++;
            }
        }
        catch(Exception e)
        {
           throw new RuntimeException("Input Error occured");
        }
        finally
        {
            inputStream.close();
        }
         
        return scoreArray;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//save new array of highscores to file
        FileWriter outputStream = null;
        try
        {
            outputStream = new FileWriter("highscores.txt", false);
            BufferedWriter bw = new BufferedWriter(outputStream);
             
            for (int k=0; k < allArray.length; k++)
            {
                bw.write(allArray[k]);
                bw.newLine();
            }
        }        
        catch (Exception e)
        {
            throw new RuntimeException("Output Error occured");
        }
        finally
        {
            outputStream.close();
        }
         
       }
Adept_Red Adept_Red

2013/12/8

#
shameless bump...
Adept_Red Adept_Red

2013/12/9

#
Alright, well after some more trail and error I keep getting this:
java.lang.RuntimeException: Input Error occured at HS_controller.loadScores(HS_controller.java:73) at HS_controller.act(HS_controller.java:31) at greenfoot.core.Simulation.actActor(Simulation.java:568) at greenfoot.core.Simulation.runOneLoop(Simulation.java:526) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205)
The lines point to the catch, but I don't know whats happened to cause an exception. >.> What is wrong?! Here is my current 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
public static int[] loadScores() //throws Exception
    {
        //load preiviously saved scores from file
        BufferedReader inputStream = null;
        int scoreArray[] = new int[5];
         
        try
        {
            inputStream = new BufferedReader(new FileReader("highscores.txt"));
            int num = 0; //line count
            String t = "";
            
            while((t = inputStream.readLine()) != null) // only if there is something to read
            {
                scoreArray[num] = Integer.parseInt(t);
                num++;
            }
        }
        catch(Exception e)
        {
           throw new RuntimeException("Input Error occured");
        }
         
        try
        {
            inputStream.close();
        }
        catch(Exception e)
        {
            throw new RuntimeException("Closing error");
        }
        return scoreArray;
    }
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
//save new array of highscores to file
        FileWriter outputStream = null;
        try
        {
            outputStream = new FileWriter("highscores.txt", false);
            BufferedWriter bw = new BufferedWriter(outputStream);
             
            for (int k=0; k < allArray.length; k++)
            {
                bw.write(allArray[k]);
                bw.newLine();
            }
        }        
        catch (Exception e)
        {
            throw new RuntimeException("Output Error occured");
        }
         
         try
        {
            outputStream.close();
        }
        catch(Exception e)
        {
            throw new RuntimeException("Closing error");
        }
         
         
         
       }
iau iau

2013/12/9

#
If you System.out.println(e) before you throw your new Exception("Input error occurred"), then you'll get more information about whether it's the FileReader() or the readLine() or the parseInt() that's causing your problem.
Adept_Red Adept_Red

2013/12/9

#
Huh... well I tried out your suggestion and oddly enough there was no error, but instead the array that is displayed was nothing but zeros. Said array is what's being returned by loadScores, so it should hypothetically contain what's in the file, not just zeroes. What could this mean?
iau iau

2013/12/9

#
If your code still looks like the above, that would be explained if there were no numbers in the file. Or, of course, if they were all 0s! How many lines do you actually read? What is the value of num when you return from loadScores?
Adept_Red Adept_Red

2013/12/9

#
Well I ran a test by adding a System.out.println(num) after the while loop. It printed out nothing but zeros! And way too many of them... This is what is in the file: 8999 4999 2999 999 1
iau iau

2013/12/10

#
So I tried the code you have given, with the highscores.txt file you gave. It works fine. So something else is going on. The only way I can see for the code you gave to read 0 numbers without causing an exception is if the file highscores.txt exists, but is empty. Are you sure that there isn't another, empty, file called highscores.txt in a different place which your program is reading?
Adept_Red Adept_Red

2013/12/10

#
I checked over the file in the project folder and it was indeed different than the one in NotePad++. However after I fixed it's contents it started giving nothing but 5s instead!!! You used my code and it worked? Odd...perhaps theres something involving the rest of the code you did differently. Perhaps there is something else altering it within the rest of the class. Hopefully someone will spot something. I'll continue running tests in the mean time to see if I can narrow it down.
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color; // Because black text isn't going to work.
import java.awt.Font; //Because default font is lame.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * Two screens, first displaying current achievments, and then high score list.
 */
public class HS_controller extends Actor
{
    private int yourScore;
    int bkcheck = 0;
 
    //constructor reciving score from HighScore
    public HS_controller(int finalScore)
    {
        yourScore = finalScore;
         
    }
 
 
    public void act()
    {
        //get array of ranks for scores
        String []ranks = setRanks();
        //get old or preset scores
        int []previousScores = loadScores();
        //draw players score and rank
        displayCurrent(yourScore, ranks);
        //sort scores and draw, then save new set of scores
        displayHOF(yourScore, previousScores);
         
    }   
     
 
    public String[] setRanks()
    {
        String rankArray[] = new String[5];
         
        rankArray[0] = "GG in Sixty Seconds";
        rankArray[1] = "National Failure";
        rankArray[2] = "Ghost Ridin";
        rankArray[3] = "Wicked Man";
        rankArray[4] = "Paulemon Master!";
         
        return rankArray;
    }
     
    public static int[] loadScores() //throws Exception
    {
        //load preiviously saved scores from file
        BufferedReader inputStream = null;
        int scoreArray[] = new int[5];
         
        try
        {
            inputStream = new BufferedReader(new FileReader("hs2.txt"));
            int num = 0; //line count
            String t = "";
            while((t = inputStream.readLine()) != null) // only if there is something to read
            {
                scoreArray[num] = Integer.parseInt(t);
                num++;
                 
            }
            System.out.println(num);
        }
        catch(Exception e)
        {
            System.out.println(e);
            throw new RuntimeException("Input Error occured");
        }
         
        try
        {
            inputStream.close();
        }
        catch(Exception e)
        {
            throw new RuntimeException("Closing error");
        }
         
        return scoreArray;
    }
 
    public void displayCurrent(int yourScore, String[] ranks)
    {
        int a = 0;
        if (yourScore <= 2000) a=0;
        if (yourScore > 2000 && yourScore <= 5000) a=1;
        if (yourScore > 5000 && yourScore <= 8000) a=2;
        if (yourScore > 8000 && yourScore <= 15000) a=3;
        if (yourScore > 15000) a=4;
         
        //multiple strings needed, as drawString cannot use 'newline'
        String dcText1 = "Experience Gained: " + yourScore;
        String dcText2 = "Your Rank: " + ranks[a];
         
        //creates a new image to drawn in
        setImage (new GreenfootImage(500, 600));
        GreenfootImage imghs = getImage(); //current image
        imghs.clear();
         
        //customizes font
        float fontSize = 30.0f;
        Font font = imghs.getFont().deriveFont(fontSize);
        imghs.setFont(font);
          
        //draws the image
        imghs.setColor(Color.WHITE);
        imghs.drawString(dcText1, 0, 150);
        imghs.drawString(dcText2, 0, 250);
         
        if (Greenfoot.isKeyDown("enter"))
        {
            imghs.clear();
        }
    }
     
    public void displayHOF(int yourScore, int[] previousScores) //throws Exception
    {
       if (bkcheck==0) bkcheck = 1;
         
       if (Greenfoot.isKeyDown("enter") && bkcheck==1)
        {
            getWorld().setBackground( new GreenfootImage("Highscore screen2.png"));
            bkcheck = 2;
        }
         
       if (bkcheck==2)
       {
        //array of all known scores to be sorted
        int allArray[] = new int[6];     
        allArray[0] = previousScores[0];
        allArray[1] = previousScores[1];
        allArray[2] = previousScores[2];
        allArray[3] = previousScores[3];
        allArray[4] = previousScores[4];
        allArray[5] = yourScore;
         
        //bubble sort for allArray
        //orders scores with yourscore for new highscore list
        int n = allArray.length;
        int temp;
         
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n-1; j++)
            {
                if (allArray[j] < allArray[j+1])
                {
                    //swapin' time!
                    temp=allArray[j];
                    allArray[j]=allArray[j+1];
                    allArray[j+1]=temp;
                }
            }
        }
         
        String hofText1 = "1. " + allArray[0];
        String hofText2 = "2. " + allArray[1];
        String hofText3 = "3. " + allArray[2];
        String hofText4 = "4. " + allArray[3];
        String hofText5 = "5. " + allArray[4];
         
        //creates a new image to drawn in
        setImage (new GreenfootImage(500, 600));
        GreenfootImage imghof = getImage(); //current image
        imghof.clear();
         
        //customizes font
        float fontSize = 20.0f;
        Font font = imghof.getFont().deriveFont(fontSize);
        imghof.setFont(font);
          
        //draws the images
        imghof.setColor(Color.WHITE);
        imghof.drawString(hofText1, 0, 100);
        imghof.drawString(hofText2, 0, 150);
        imghof.drawString(hofText3, 0, 200);
        imghof.drawString(hofText4, 0, 250);
        imghof.drawString(hofText5, 0, 300);
         
        if (Greenfoot.isKeyDown("escape"))
        {
            Greenfoot.setWorld(new Start_Screen());
                 
        }
         
        /*************************************************************************************************/
        //save new array of highscores to file
        FileWriter outputStream = null;
        try
        {
            outputStream = new FileWriter("hs2.txt", false);
            BufferedWriter bw = new BufferedWriter(outputStream);
             
            for (int k=0; k < allArray.length; k++)
            {
                bw.write(allArray[k]);
                bw.newLine();
            }
        }        
        catch (Exception e)
        {
            throw new RuntimeException("Output Error occured");
        }
         
         try
        {
            outputStream.close();
        }
        catch(Exception e)
        {
            throw new RuntimeException("Closing error");
        }
         
         
         
       }
        
    }
     
}
Adept_Red Adept_Red

2013/12/10

#
Ok, to clear something up, it was indeed printing 0s because there were no lines to read. So printing 5s is good becuase it acknowledges it has read every line. On the second run the txt file is blank again. It's deleting its own contents? Or rather, overriding them? Perhaps the file reads successfully, but cannot save correctly, so when it reloads it finds nothing. So strange...
You need to login to post a reply.