java arraylist indexoutofboundsexception索引:1,大小:1

pzfprimi  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(414)

我正在尝试用java读取某个文件,并将其放入多维数组中。每当我从脚本中读取一行代码时,控制台就会说:

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|

其他解决方案,比如这里的解决方案:在java中不重写地写入文本文件
提前谢谢。

lkaoscv7

lkaoscv71#

问题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];
    }
  }
bcs8qyzn

bcs8qyzn2#

问题出现在这里:

... guildsArray.get(x) ...

但原因是:

int x = 1;
while (scanner.hasNextLine()) {
   ...

因为集合和数组是基于零的(第一个元素是索引) 0 ).
试试这个:

int x = 0;

相关问题