0

I would like to know how to split a field through array using Java. For example we have GLaccount like AAAA-BBBB-CCCC and we would like to split each component and store it in an variable however the GLaccount may have AAAA-BBBB (no third component) so in this case variable segment3 throws NULL POINTER exception so I am not sure on how to fix this since I am new to Java.

String GL = getOwner().getGL("GLACCT");
String segment1 = GL.split("-")[0];
String segment2 = GL.split("-")[1];
String segment3 = GL.split("-")[2]; 
1
  • If you get a nullpointer as you say, then there is something else wrong, you should get an index out of bounds exception, check that getGL is not null. Commented Oct 17, 2018 at 20:38

3 Answers 3

1

Using split("-" ) will give you an array of strings. before using array value, you can check the size of array that if it contains enough elements to use..

String GL = getOwner().getGL("GLACCT"); 
String[] array=GL.split("-");
String segment1 = array[0]; 
String segment2 = array[1]; 

//check if array have 3rd element 
if(array.length >2)
      String segment3 = array[2];
else
       System.out.println("No third element") ;
Sign up to request clarification or add additional context in comments.

Comments

0

Use split method (once) and check returned array length :

 String[] values3 = "AAAA-BBBB-CCCC".split("-");
 // values.length == 3 


 String[] values2 = "AAAA-BBBB".split("-");
 // values2.length == 2 

Comments

0
import java.util.Arrays;    
List<String> list = Arrays.asList(GL.split("-"));

With this code you do not need to think if you have 2,3 or 10 strings, and to add new if for every new one.

1 Comment

Add some description to your code, code only answeres are mostly not acceptable

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.