Java ArrayList IndexOutOfBoundsException索引:1,大小:1
问题描述:
我试图读取Java中的某个文件,并将其制作成多维数组。每当我从脚本读取一行代码,控制台说:Java ArrayList IndexOutOfBoundsException索引:1,大小:1
Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
我知道这个错误是,当编码无法达到的具体指标造成的,但我不知道如何在修复此时此刻。
这是我编码的一个例子。
int x = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Explode string line
String[] Guild = line.split("\\|");
//Add that value to the guilds array
for (int i = 0; i < Guild.length; i++) {
((ArrayList)guildsArray.get(x)).add(Guild[i]);
if(sender.getName().equals(Guild[1])) {
//The person is the owner of Guild[0]
ownerOfGuild = Guild[0];
}
}
x++;
}
**文本文档**
Test|baseman101|baseman101|0|
Test2|Player2|Player2|0|
其他解决方案,比如一个在这里找到:Write to text file without overwriting in Java
在此先感谢。
答
问题1 - >int x = 1;
解决方案:x应为0
问题来开始2->
((ArrayList)guildsArray.get(x)).add(Guild[i]);
您正在增加x
如此if x >= guildsArray.size()
那么你将得到java.lang.IndexOutOfBoundsException
解决方案
if(x >= guildsArray.size())
guildsArray.add(new ArrayList());
for (int i = 0; i < Guild.length; i++) {
((ArrayList)guildsArray.get(x)).add(Guild[i]);
if(sender.getName().equals(Guild[1])) {
//The person is the owner of Guild[0]
ownerOfGuild = Guild[0];
}
}
答
的问题发生在这里:
... guildsArray.get(x) ...
但这里引起的:
int x = 1;
while (scanner.hasNextLine()) {
...
由于类别和阵列从零开始(第一个元素是索引0
)。
试试这个:
int x = 0;
好,异常说发生了什么异常时的水平。数组大小为1,您访问位置1.您的逻辑不正确! – diegoaguilar
我以为ArrayLists动态增加? – baseman101
他们确实增加dinamically,但他们是0基于和访问比实际更大的索引将导致异常 – diegoaguilar