Java ArrayList IndexOutOfBoundsException索引:1,大小:1
我试图用Java读取某个文件,并将其放入多维数组中。每当我从脚本中读取一行代码时,控制台就会显示:Java ArrayList IndexOutOfBoundsException索引:1,大小:1,java,arrays,file,arraylist,bukkit,Java,Arrays,File,Arraylist,Bukkit,我试图用Java读取某个文件,并将其放入多维数组中。每当我从脚本中读取一行代码时,控制台就会显示: Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 我知道这个错误是由于编码无法达到特定的索引而导致的,但我现在不知道如何修复它 下面是我的编码示例 int x = 1; while (scanner.hasNextLine()) { String line = scanner.nextLine(); //E
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++;
}
其他解决方案,如此处所示:
提前感谢。问题出现在这里:
... guildsArray.get(x) ...
但原因在于:
int x = 1;
while (scanner.hasNextLine()) {
...
因为集合和数组是基于零的(第一个元素是index0
)
试试这个:
int x = 0;
问题1->
intx=1代码>
解决方案:x应该以0开头
问题2->
((ArrayList)guildsArray.get(x)).add(Guild[i]);
您正在增加x
因此如果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];
}
}
if(x>=guildsArray.size())
添加(新的ArrayList());
for(int i=0;i
好吧,异常表示在异常级别发生了什么。数组大小为1,您可以访问位置1。你的逻辑不正确!我认为ArrayList是动态增加的?它们确实是动态增加的,但是它们是基于0的,访问比实际索引更大的索引会导致异常,这真的救了我的命。
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];
}
}