在我的代码中
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);
}
我的submenuCap.toString.length()
中有30个,有些值类似于""
,"LOTO Equipment Issue & Return Record*0"
和"Some Equipment Issue & Return Record*1"
等。
我想只在数据!= ""
时拆分,然后根据数据得到0或1的最后一个索引值,但这里我得到的是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)
答案 0 :(得分:0)
如果split函数返回一个包含至少两个元素的数组,只需添加一个检查。
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);
}
}
答案 1 :(得分:0)
添加并检查条件
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
}
}