King Aslan
King Aslan

Reputation: 169

Getting an ArrayIndexOutOfboundsException when splitting a string into an array and then looping over it

I am trying to send the result of a split() function into an array of strings, but I am getting an exception as follows:

java.lang.ArrayIndexOutOfBoundsException: somenumber

I am using the following code, but it returns that exception:

String[] temp;
temp = result.split(" ");

Any suggestions? I want to send the result of the string split() function into an array of strings, and then print the values in a for loop.

I am getting an out of bounds exception in for loop, I use:

for (int i=0;i<=temp.length;i++)
{
    out.println(temp[i]);
}

Upvotes: 0

Views: 2784

Answers (5)

user1181445
user1181445

Reputation:

String temp;
String[] split = result.split(" ");
temp = split[temp.length - 1];

You were declaring a String array as a single string, then declaring a new String in the wrong way.

EDIT: saw you updated your post:

You have to use less then for the condition in the for loop. If an array has 5 elements, the last element will be 4, not 5. The correct code is:

for(int i = 0; i < temp.length; i++){
  System.out.println(temp[i]);
}

You can even do:

for(String cur : temp){
  System.out.println(cur);
}

Upvotes: 3

Andr&#233;s Oviedo
Andr&#233;s Oviedo

Reputation: 1428

If you want to store the result (length of the array?) in the same array that generated the split() function, then you can't. You would have to create another array of bigger length:

String result = "Hello World";
String[] temp;
temp = result.split(" ");
String[] temp2 = Arrays.copyOf(temp, temp.length + 1);
temp2[temp.length] = String.valueOf(temp.length);
System.out.println(Arrays.toString(temp2));

The output is: [Hello, World, 2]

Upvotes: 0

gpeche
gpeche

Reputation: 22524

This?

String[] parts = original.split(" ");

Upvotes: 0

Guillaume Polet
Guillaume Polet

Reputation: 47627

Your code can't work like that. split returns String[].

String someString = "hello world";
String[] split = someString.split(" ");
String hello = split[0];
String world = split[1];
String lastWord = split[split.length-1];

Upvotes: 0

talnicolas
talnicolas

Reputation: 14053

The split() method (doc) returns an Array of String, so your temp variable should be a String[].

Upvotes: 0

Related Questions