gpt4 book ai didi

java - 在循环内创建对象

转载 作者:行者123 更新时间:2023-12-02 01:57:03 26 4
gpt4 key购买 nike

我正在制作一个基于文本的游戏,但在循环内创建对象时遇到问题

这是我的代码

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++;
}

问题是数组中只存储了 1 个技能,我不知道如何解决这个问题。

最佳答案

主要问题在这里:

Skill_List = new Skill[] { new Skill(Name, Type, Desc, Skill_Level, Effect, Effect2, Manacost, Cooldown, Skill_From, Power_Gain) };

您每次都会覆盖旧的 Skill_List 变量,因此您只有 1 项。你可以这样做:

Skill_List[j] = new Skill(Name, Type, Desc, Skill_Level, Effect, Effect2, Manacost, Cooldown, Skill_From, Power_Gain);

但在此之前,您需要提前知道数组将容纳多少项,并使用该数量创建数组。所以你会改变

Skill[] Skill_List = null;

Skill[] Skill_List = new Skill[10];

但这限制了你只能使用 10 种技能。更好的选择是使用List。这些容器可以容纳可变数量的数据。

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));

每次调用 add 时,列表都会增加 1。如果您确实想要一个数组,可以在构建列表后调用 toArray() 函数.

关于java - 在循环内创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com