Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList IndexOutOfBoundsException Index: 1, Size: 1

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:

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

Thanks in advance.

like image 824
baseman101 Avatar asked Jan 13 '23 02:01

baseman101


2 Answers

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

problem 2->

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

You are increasing x so if x >= guildsArray.size() then you will get 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];
    }
  }
like image 124
Prabhakaran Ramaswamy Avatar answered Jan 22 '23 01:01

Prabhakaran Ramaswamy


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).

Try this:

int x = 0;
like image 43
Bohemian Avatar answered Jan 22 '23 02:01

Bohemian