I'm trying to read in player data from an array list, but after 2 hours of searching and experimenting, I'm lost.
Here's the deserializing code. It's commented, but basically there should be a file with a Serialized ArrayList of Player objects. I want to deserialize that data and store it in savedPlayers, and then use savedPlayers for a few things.
What did I do wrong?
import java.io.*;
import java.util.*;
public class RoofRunnerApp {
private Scanner in; // Scanner to take playerName input.
private RoofRunnerGame gameTime;
private String filename = "gameData.txt";
public static void main (String[] args) {
System.out.println("WELCOME TO *ROOF RUNNER* \n"); // Welcomes user with game title.
RoofRunnerApp myGame = new RoofRunnerApp();
}
public RoofRunnerApp() {
// 1) Read in name from user.
in = new Scanner(System.in);
System.out.print("Please enter your name: ");
String playerName = in.next();
// 2) Create Player arrayList.
ArrayList<Player> savedPlayers = new ArrayList<Player>();
// 3) Read in Serialized Data from file.
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(filename)); // Add file name.
savedPlayers = (ArrayList<Player>)input.readObject();
input.close();
} catch( Exception e ) {
e.printStackTrace();
return;
}
Player thisPlayer; //thisPlayer is passed to Game class.
// 4) if arraylist != empty -> Check for playerName and inputName match.
////// If there's a match -> Set thisPlayer equal to the savedPlayer, using the Player constructor.
if(savedPlayers.length() != 0)
for(int i = 0; i < savedPlayers.length(); i++)
if(playerName.equals(savedPlayers.getName())){
thisPlayer = new Player(savedPlayers[i]);
break;
}
}
else
thisPlayer = new Player(playerName); // If no match -> Set thisPlayer to new player with playerName.
RoofRunnerGame gameTime = new RoofRunnerGame(thisPlayer);
}