【问题标题】:Java ArrayList IndexOutOfBoundsException Index: 1, Size: 1Java ArrayList IndexOutOfBoundsException 索引:1,大小:1
【发布时间】:2013-10-28 00:52:26
【问题描述】:

我正在尝试用 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|

其他解决方案,例如在此处找到的解决方案:Write to text file without overwriting in Java

提前致谢。

【问题讨论】:

  • 嗯,异常说明了异常级别发生的事情。数组大小为 1,您访问位置 1。您的逻辑不对!
  • 我以为 ArrayLists 是动态增加的?
  • 它们确实会增加,但是它们是基于 0 的,并且访问比实际更大的索引会导致异常

标签: java arrays file arraylist bukkit


【解决方案1】:

问题 1 -> int x = 1;
解决方法:x应该以0开头

问题 2->

((ArrayList)guildsArray.get(x)).add(Guild[i]);

你正在增加x 所以if x &gt;= 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];
    }
  }

【讨论】:

  • 这真的救了我的命。
【解决方案2】:

问题出现在这里:

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

但是是这里引起的:

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

因为集合和数组都是从零开始的(第一个元素是索引0)。

试试这个:

int x = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2018-02-13
    • 1970-01-01
    • 2015-04-15
    • 2016-10-09
    • 2020-10-27
    • 2015-05-07
    相关资源
    最近更新 更多