Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using an array to create a string

Tags:

java

arrays

split

I'm having an issue with some of my code. I'm receiving a date in the dd/mm/yyyy format as a string called dateofQ.

I want the date to be yyyy_mm_dd, I'm using a string.split() into an array, but it wont return the 3rd array called myArr[3]:

String[] myArr = dateofQ.split("\\/");
String dateFormat = String.format("%s_%s_%s",myArr[2],myArr[1],myArr[0]);

It returns myArr[1] and myArr[0], but when I also add myArr[3] I get an issue at runtime:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at ReadFile.main(ReadFile.java:34)
like image 637
Chris Avatar asked Dec 27 '22 16:12

Chris


1 Answers

Well, the array only has 3 elements, and myArr[3] is trying to get the fourth element (remember, arrays are zero-indexed).

To get the third element, use myArr[2].

like image 182
nneonneo Avatar answered Jan 08 '23 11:01

nneonneo