0

i am trying to make a highscore for a hangman game. So i need to save it so it doesnt restart everytime u start the game or return to the menu.. so I have a playstate that records the wins and losses at the end of the game and if the user leaves before solving it adds a loss. I found a tutorial to save via a SavaData file.. the problem is it saves an empty file nothing in there but has 2 empty lines.. and so i get a numberformatexception null.. i had it working before but it still would not read the line and would return an error numberformatexception Integer.parseInt.. I know the problem is in reading lines and now i dont know what went wrong please help me .. whats wrong with the code?? thanx

this is the saving code...

 private void createSaveData() {

        File file = new File(saveDataPath, filename);
        try {

            FileWriter output = new FileWriter(file);
            BufferedWriter writer = new BufferedWriter(output);
            writer.write("" + 0);
            writer.newLine();
            writer.write("" + 0);

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

    }

    private void setScores() {

        FileWriter output = null;

        try {

            File F = new File(saveDataPath, filename);
            output = new FileWriter(F);
            BufferedWriter writer = new BufferedWriter(output);
            writer.write(wins);
            writer.newLine();
            writer.write(losses);
            writer.close();

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

private void loadScores() {
    try {

        File F = new File(saveDataPath, filename);

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(F)));

        String line = reader.readLine();

        line = reader.readLine();
        wins = Integer.parseInt(line);

        line = reader.readLine();
        losses = Integer.parseInt(line);

        reader.close();


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

}

i then add loadScore(); at the begging of the playstate.. and setScore(); after a win++ or a loss++..

i have another highscorestate that calls on playstate and gets the wins and lossess as an integer and that works no problems cause it draws 0 , 0 .

in my render method i have this if the tries are too much or if the correct answer is guessed...

    if (tries == 6) {

        currentWord = ranWord;
        execcurrentframe.setRegion(eman.ExecLoss.getKeyFrame(elapsedTime, false));
        hangcurrentframe.setRegion(hman.hangdead.getKeyFrame(elapsedTime, false));
        Wordsfont.draw(batch, "Game Over", eman.getPosition().x + 60, hman.getPosition().y + 70);
        batch.draw(fu, 160, 510);

        if (leverpressed == false){

            bksound.stop();
            lever.play();
            leverpressed = true;

        }

        if (lossrecorded == false) {
            losses += 1;
            System.out.print("Losses = " + losses);
            setScores();
            lossrecorded = true;

        }
    }
    else if (CorrectAnswer == true) {
        hangcurrentframe.setRegion(hman.hangwin.getKeyFrame(elapsedTime, false));
        Wordsfont.draw(batch, "You Won", eman.getPosition().x + 60, hman.getPosition().y + 70);


        if (winrecorded == false) {
            bksound.stop();
            victory.play();
            wins += 1;
            System.out.print("Wins = " + wins);
            setScores();
            winrecorded = true;

        }
    }
Joe
  • 65
  • 1
  • 8
  • One comment, be sure to close the writer in `createSaveData()`. You should also put all of the `.close()` method calls in a finally block, or use the Java 7 try-with-resources approach. – KevinO May 13 '16 at 18:38
  • i noticed that too even though in the tutorial he didnt add.. still doesnt help only changed the error too .lang.NumberFormatException: For input string:"" + plus the reading problem.. java.lang.Integer.parseInt(Integer.java:481) – Joe May 13 '16 at 18:41
  • (1) Are you using both `createSaveData` and `setScores`? What is the type of `wins` and `losses`? – RealSkeptic May 13 '16 at 18:45
  • i added the wins loss to the question – Joe May 13 '16 at 18:53

2 Answers2

0

You have overlooked one important part of the original createSaveData method:

writer.write("" + 0);

See that "" + 0? It effectively converts the integer to a string (though there are more elegant ways of doing this).

BufferedWriter has overloaded write method. This means there is a different method that is called when the parameter is a String, and a different one when the parameter is an int.

You have called the version whose parameter is an int. Its documentation says:

public void write(int c) throws IOException

Writes a single character.

Overrides:

write in class Writer

Parameters:

c - int specifying a character to be written

Throws:

IOException - If an I/O error occurs

This tells you that it considers the int that you passed as a character. That is, if you give it the int 65, it will be taken as the character A. If you give it the int 48, it will be taken as the character 0.

If you give it the integer 0, this is the NUL control character.

When you read that back as a string, it is taken as a single-character string containing the NUL character. Of course, that's not a valid string format for a number.

So replace

        writer.write(wins);

With

        writer.write(String.valueOf(wins));

And do the same for losses.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
  • thank you for the info ... im new to this but i understand what ur saying i turned the integer to a string and then called on it as an int.. gonna try the below method since it combines my two methods.. if not will do this one – Joe May 13 '16 at 19:02
0

I would suggest the following changes.

  1. Use a single writeSaveData method. The code between createSaveData and setScores is largely duplicated. Also, use the Integer.toString() to write the output. Also, ensure the stream is closed (here using try with resources).

    private void writeSaveData(int wins, int losses)
    {
      File file = new File(saveDataPath, filename);
      try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
        writer.write(Integer.toString(wins));
        writer.newLine();
        writer.write(Integer.toString(losses));
    
      }
      catch (Exception e) {
          e.printStackTrace();
      }
    
    }
    
  2. There is an extra readLine() in the loadScores() method. Remove that extra line. Change to use try with resources.

    private void loadScores()
    {
      File file = new File(saveDataPath, filename);
    
      try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
        String line = reader.readLine();
    
        // line = reader.readLine() <-- REMOVE THIS LINE
        wins = Integer.parseInt(line);
    
        line = reader.readLine();
        losses = Integer.parseInt(line);
    
        reader.close();
    
    
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
    

EDIT: If one cannot use try with resources, then the following approach may be used instead.

private void loadScores()
{
    File file = new File(saveDataPath, filename);

    BufferedReader reader = null;
    //        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));            
        String line = reader.readLine();

        wins = Integer.parseInt(line);

        line = reader.readLine();
        losses = Integer.parseInt(line);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        if (reader != null) {
            try {
                reader.close();
            }
            catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

A similar modification may be made to the suggested writeSaveData() or other methods.

KevinO
  • 4,303
  • 4
  • 27
  • 36
  • getting an error saying Try with resources is not supported at this language level?? is that a version issue or just the wrong imported library? ty for you help – Joe May 13 '16 at 19:03
  • i changed the vs. to 1.7 but still gettting an error.. any idea y?? using android studios – Joe May 13 '16 at 19:15
  • I am not sure how you are compiling (i.e., IDE, javac, etc). If the try with resources is not available, you can move the declarations outside of the try, and then add a finally { } to close them. I will try to update the answer in a moment. – KevinO May 13 '16 at 20:05
  • WRT to the Java, version and android studio, [this link may help](http://stackoverflow.com/questions/23318109/is-it-possible-to-use-java-8-for-android-development) – KevinO May 13 '16 at 20:25
  • Hey Kevin.. I dont understand what u did.. or most of the code but I LOVE U man it works.. thats it IM done with my first game.. – Joe May 13 '16 at 22:50