Reputation: 23
I am making a texted based game and I have problem creating objects inside a loop
here is my code
int i = 1;
Skill[] Skill_List = null;
String[] Skill_Info;
File directory = new File("D:\Program Files\Game_dev2\src\Database\Skills");
int FileCount = directory.list().length;
while (i < FileCount - 1) {
Scanner Skill_Info_Data = new Scanner(
new File("D:\Program Files\Game_dev2\src\Database\Skills\Skill" + (i) + ".csv"));
int j = 0;
while (Skill_Info_Data.hasNext()) {
Skill_Info = Skill_Info_Data.nextLine().split(",");
String Name = Skill_Info[0];
String Type = Skill_Info[1];
String Desc = Skill_Info[2];
int Skill_Level = Integer.parseInt(Skill_Info[3]);
int Effect = Integer.parseInt(Skill_Info[4]);
int Effect2 = Integer.parseInt(Skill_Info[5]);
int Manacost = Integer.parseInt(Skill_Info[6]);
int Cooldown = Integer.parseInt(Skill_Info[7]);
String Skill_From = Skill_Info[8];
int Power_Gain = Integer.parseInt(Skill_Info[9]);
Skill_List = new Skill[] { new Skill(Name, Type, Desc, Skill_Level, Effect, Effect2, Manacost, Cooldown,
Skill_From, Power_Gain) };
j++;
}
i++;
}
The problem is that the there is only 1 skilled stored in the array and I am running out of idea on how to fix this.
Upvotes: 0
Views: 68
Reputation: 13533
The main issue is here:
Skill_List = new Skill[] { new Skill(Name, Type, Desc, Skill_Level, Effect, Effect2, Manacost, Cooldown, Skill_From, Power_Gain) };
You overwrite the old Skill_List
variable each time so you only ever have 1 item. You could do this:
Skill_List[j] = new Skill(Name, Type, Desc, Skill_Level, Effect, Effect2, Manacost, Cooldown, Skill_From, Power_Gain);
But before you can do that, you need to know ahead of time how many items the array will hold, and create the array with that amount. So you would change
Skill[] Skill_List = null;
to
Skill[] Skill_List = new Skill[10];
But this limits you to 10 skills. The better option is to use a List
. These containers can hold a variable amount of data.
ArrayList<Skill> Skill_List = new ArrayList<Skill>(); // Create empty list
//...
Skill_List.add(new Skill(Name, Type, Desc, Skill_Level, Effect, Effect2, Manacost, Cooldown, Skill_From, Power_Gain));
Each time you call add
the list grows by 1. If you really want an array, you can call the toArray()
function after you've built the list.
Upvotes: 2