0

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]);
}
3
  • 3
    What does this relate to javascript? Commented Mar 30, 2012 at 14:48
  • 1
    The code you've provided wouldn't even compile, as you can't assign a string array to a String variable. Please post a short but complete program which does compile. Commented Mar 30, 2012 at 14:49
  • @King Aslan, see my edited answer: it should explain fairly well on why the new error is happening. Commented Mar 30, 2012 at 15:05

5 Answers 5

3
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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. If you want, feel free to do some challenges on CodingBat. They are good for these type of methods and will help explain. I am currently making a similar program but offline.
0

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

Comments

0

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

Comments

0

This?

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

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.