I am very new to Java and although my code works, I know that it must be possible to write this using fewer lines of code. I am serializing multiple objects, eventually I will look into serializing to multiple files, for now, I am using just one file, so it constantly gets over-written. How can I nest or reduce the number of if statements I am using. In my code snippet, I am using an if statement for each individual object, and duplicating my try/catch block. This is horrible code, but I am stumped as to how I can write this more efficiently.
In very simple terms, please give me an example of how to nest or reduce code duplication. I shouldn't need to re-do my try/catch block constantly!
public class Serializer
{
public void Serialize()
{
MainMenu pass_choice = new MainMenu();
int passed_choice = pass_choice.chooseTeam();
if(passed_choice==1){
ClubInfo club = new ClubInfo();
club.teamName = "Arsenal";
club.stadium = "Emirates";
club.division = "Premier League";
club.SSN = 11122333;
club.stadiumCapacity = 60000;
try
{
FileOutputStream fileOut =
new FileOutputStream("/home/cg/root/club.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in C:/tmp/club.ser");
System.out.println("Choice is :" + passed_choice);
}catch(IOException i)
{
i.printStackTrace();
}
} // end if 1
else
if(passed_choice==2){
ClubInfo club1 = new ClubInfo();
club1.teamName = "Aston Villa";
club1.stadium = "Villa Park";
club1.division = "Premier League";
club1.SSN = 111223334;
club1.stadiumCapacity = 40000;
try
{
FileOutputStream fileOut =
new FileOutputStream("/home/cg/root/club.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(club1);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in C:/tmp/club.ser");
System.out.println("Choice is :" + passed_choice);
}catch(IOException i)
{
i.printStackTrace();
}
} // end if 2
}
}