0

In my code

for(int i=1; i<submenuCap.toString().length();i++){
     String[] parts = captionRes.getString(i).split("[*]");
     String part1 = parts[0]; 
     String part2 = parts[1];
    System.out.println("First parts: "+part1+" 2nd Part: "+part2);
 }  

Here in my submenuCap.toString.length() is 30, and some values are like "", "LOTO Equipment Issue & Return Record*0" and "Some Equipment Issue & Return Record*1" etc..

I want to split only when data != "", then get last index values either 0 or 1 according to data, but here I am getting o/p

 First parts: LOTO Energy Isolation Record 2nd Part: 0
 First parts: LOTO Equipment Issue & Return Record 2nd Part: 0
 First parts: UPS Visitor Entry Record 2nd Part: 0
 First parts: Daily Technical Observation Record 2nd Part: 0
 java.lang.ArrayIndexOutOfBoundsException: 1
 at com.dao.DaoImpl.getMappingCategoryData(DaoImpl.java:240)
 at com.services.ServiceImpl.getMappingCategoryData(ServiceImpl.java:30)
 at com.controller.MasterController.getMappingCategoryData(MasterController.java:71)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Welcome to Stack Overflow! It looks like you need to learn to use a debugger. Please help yourself to some [complementary debugging techniques](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). If you still have issues afterwards, please feel free to come back with a more specific question. – Joe C Jul 29 '17 at 06:21
  • 1
    Please use full words, for example, what does _getting o/p_ mean? – Mark Rotteveel Jul 29 '17 at 07:31

2 Answers2

0

Just add a check if split function returns an array having atleast two elements.

for(int i=1; i<submenuCap.toString().length();i++){
     String[] parts = captionRes.getString(i).split("[*]");
     if(parts.length >1){ // check added.
        String part1 = parts[0]; 
        String part2 = parts[1];
        System.out.println("First parts: "+part1+" 2nd Part: "+part2);
     }
 } 
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
0

Add and check the conditions

  for(int i=0; i<submenuCap.toString().length();i++){
       if(captionRes.getString(i)!=null&&!captionRes.getString(i).isEmpty()){
          String[] parts = captionRes.getString(i).split("[*]");
          //It would be better checking array size before processing by index
          String part1 = parts[0]; 
          String part2 = parts[1];
          System.out.println("First parts: "+part1+" 2nd Part: "+part2);
      }else{
          //Other logic      
      }
   } 
Lakshman Miani
  • 344
  • 1
  • 5
  • 20