Java ArrayList IndexOutOfBoundsException 索引:1,大小:1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19462184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:27:43  来源:igfitidea点击:

Java ArrayList IndexOutOfBoundsException Index: 1, Size: 1

javaarraysfilearraylistbukkit

提问by baseman101

I'm attempting to read a certain file in Java and make it into a multidimensional array. Whenever I read a line of code from the script, The console says:

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

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

I know that this error is caused when the coding can't reach the specific index, but I have no idea how to fix it at the moment.

我知道这个错误是在编码无法到达特定索引时引起的,但我目前不知道如何修复它。

Here is an example of my coding.

这是我的编码示例。

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++;
}

**Text Document **

**文本文件**

Test|baseman101|baseman101|0|
Test2|Player2|Player2|0|

Other solutions, such as the one found here: Write to text file without overwriting in Java

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

Thanks in advance.

提前致谢。

采纳答案by Prabhakaran Ramaswamy

problem 1 -> int x = 1;
solution: The x should be start with 0

问题 1 ->int x = 1;
解决方案:x 应该从 0 开始

problem 2->

问题 2->

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

You are increasing xso if x >= guildsArray.size()then you will get java.lang.IndexOutOfBoundsException

你在增加, x所以if x >= guildsArray.size()你会得到java.lang.IndexOutOfBoundsException

solution

解决方案

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];
    }
  }

回答by Bohemian

The problem is occurring here:

问题发生在这里:

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

but is caused here:

但是是在这里引起的:

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

Because Collections and arrays are zero-based (the first element is index 0).

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

Try this:

尝试这个:

int x = 0;