Using an array to create a string

I have a problem with some of my code. I get the date in dd/mm/yyyy format as a string named dateofQ .

I want the date to be yyyy_mm_dd , I use string.split() in the array, but it will not return a third array named 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 a problem at runtime:

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ReadFile.main(ReadFile.java:34) 
+4
source share
4 answers

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

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

+6
source

It seems that the length of myArr no more than 2.

Please make sure myArr.length at least 3.

Insert

 System.out.println(myArr.length); 

right after:

 String[] myArr = dateofQ.split("\\/"); 

is an easy way to check it out.

+2
source

I probably missed something really obvious, but could you just do something like ...

 try { String dateofQ = "08/03/1972"; SimpleDateFormat in = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat out = new SimpleDateFormat("yyyy_MM_dd"); dateofQ = out.format(in.parse(dateofQ)); System.out.println(dateofQ); } catch (ParseException ex) { ex.printStackTrace(); } 

Which of these puts 1972_03_08

+2
source

ArrayIndexOutOfBoundsException: 2 This error means that you have an array of less than 3 elements and you are trying to access the third. that is, you get the error @ myArr[2] .

What you need to do is first check the length of the array and then access it. If an invalid array rejects it.

 if(myArr.length==3)//Process else you need to reject 

It is best to use the method specified in MadPorgrammer's answer.

0
source

Source: https://habr.com/ru/post/1437737/


All Articles