0

In my Java game, I would like to be able to display the user's name, win score and lose score when it's game over. For example:

How it should look

Even after the game has been exited and then recompiled and run again, the info from the text file would be read into the program and added to the arrays. At the end of that game, the list will grow longer and then the text file will have the updated info for the next game.

Thanks so much in advance

G. Bea
  • 25
  • 1
  • 2
  • 8

1 Answers1

0

assuming the arrays are of the same length and each individual index is associated with the same player just use one for loop and write each item at the index in the three arrays to a file separated by commas then you can read back into file the same way you wrote into the file

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("NAME W L");
writer.println("--------");
for(int i=0; i<a.length; i++){
   writer.println(a[i] + ", " + b[i] + ", " + c[i] ); 
}

Then before each game just read the text file back into to the arrays splitting on the commas and trimming white space and taking each string leftover and writing it back into the right arrays(make sure you cast to the right types if you want ints). Also you should probably use ArrayLists instead of arrays if they are going to be growing and you don't know the size they are going to grow to.

There are many ways to read and write to files but this is probably the general pattern you want to follow for your needs.

James Russo
  • 578
  • 3
  • 18
  • 1
    And [here's an answer](http://stackoverflow.com/questions/10960213/how-to-read-comma-separated-values-from-text-file-in-java) on how to read a CSV (comma-separated value) file. : ) – Frecklefoot Jun 10 '16 at 19:02