-1

I do split to a String, but I did not consider the exception. So the error comes out. For example, if the string is "2012-10-21,20:00:00,,"

Here is the codes:
String str = "2012-10-21,20:00:00,,";
String a[] = str.split(",");
String timestamp = a[0] + "T" + a[1];
String temp = a[2];


System.out.println(timestamp);
System.out.println(temp);

Here is the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2

Actually, a[2] is null, but I don't know how to deal with this problem. Because in my String Array, some recodes contains the value of temp, such as "2012-10-21,20:00:00,90,".

Thank you.

Eric
  • 1,271
  • 4
  • 14
  • 21

2 Answers2

7

split does remove empty elements. You need to use the two parameter version:

str.split(",",-1);

See here: Java String split removed empty values

Community
  • 1
  • 1
michael81
  • 206
  • 2
  • 8
0

Your problem is in this line of code

String temp = a[2];

It appears that you only have 2 elements, and a[2] references the third element in the array because the indexing begins at 0, not 1. Your 3rd element is actually removed because it is empty.

If you want to get the size of an array to keep yourself from going out of bounds, you can call the sizeof function on your array.

int main(){

      int myarray[3]; //an array of 3 intigers for example

      cout << sizeof(myarray); //print the array size in bytes
]

The output of this will be "12"

The output is 12 because sizeof will return the size of the array, not the number of elements, so int the case of ints, which are 4 bytes, you get 12.

Gavin Perkins
  • 685
  • 1
  • 9
  • 28
  • Thank you for your response. I have a String Array, some recodes contains temp, so would not have error. However, some recodes like this, no temp value, will lead to out of bound exception. So how could I print all of them without error. – Eric Aug 26 '13 at 15:05
  • In general always, really always check the array length first before you make assumption, this would not only avoid any errors, but is really important for quality code. – michael81 Aug 26 '13 at 15:21
  • To get the size of an array, you can just call the "sizeof" method on the array. Be careful, because the size returns the size of each object in the array, so if you have an array of 3 ints, sizeof will return the number 12 because an int is 4 bytes long. – Gavin Perkins Aug 28 '13 at 21:56