gpt4 book ai didi

java - 不知道为什么JAVA数组会越界

转载 作者:行者123 更新时间:2023-12-01 22:41:56 25 4
gpt4 key购买 nike

我在运行时在 String Weapon = dataz[1]; 行上遇到数组索引越界异常。我不确定是什么原因造成的,因为这与我在之前的作业中使用的代码几乎相同。任何关于为什么会发生这种情况的逻辑都将不胜感激!

public Hero[] getHeroes(){

String file = getFilePath();
Hero[] heroPower = new Hero[5];

int i=0;
try{
Scanner data = new Scanner(file);
while(data.hasNextLine() && i < 5)
{
String next = data.nextLine();
if(!next.trim().isEmpty())
{
String[] derp = next.split(",");
String name = derp[0];
String weapon = derp[1];
int attackPoints = Integer.parseInt(derp[2]);
heroPower[i] = new Hero(name,weapon,attackPoints);
i++;
}
}
data.close();
} finally {

}
return heroPower;
}
}

最佳答案

您的下一个字符串可能不会拆分。它没有 , 并且您没有检查该选项。

关于java - 不知道为什么JAVA数组会越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26000103/

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