【发布时间】:2015-09-13 00:39:47
【问题描述】:
我写了一个方法来定期在字符串数组中插入一个字符。 我在android studio中编写了它,应用程序停止运行。 我的输入是一个字符串数组:(输入的部分只是为了测试,我会动态的)
String[] myPoints= new String[4];
myPoints[0]="22";
myPoints[1]="45";
myPoints[2]="34";
myPoints[3]="60";
现在我需要在数组的每两条记录之间插入“,”。所以我写了这个:
public static String[] insertPeriodically(String[] points){
int pointsSize = points.length;// length of points array
int withCommosSize=pointsSize+(pointsSize/2)-1;//length of new array
String[] withCommos= new String[withCommosSize];
int insert=0;
int k=0;
for (int i=0; i<pointsSize; i=i++){
withCommos[k]=points[i];
insert=insert+1;
if(insert==2){
withCommos[k+1]=",";
k++;
insert=0;
}else
k++;
}
return withCommos;
}
控制台显示此 java 错误: java.lang.RuntimeException:无法启动活动 ComponentInfojava.lang.ArrayIndexOutOfBoundsException:长度 = 5;索引=5
您有什么建议吗?
【问题讨论】:
-
你试过把这个
int withCommosSize=pointsSize+(pointsSize/2)-1改成int withCommosSize=pointsSize+(pointsSize-1) -
and the application stops running为什么?例外?如果是这样 - 请添加完整的堆栈跟踪。 -
IndexOutOfBoundException 是相当清楚的......为什么不使用一个随着数据增长的数组,比如一个列表?
-
因为这个方法它停止运行,因为当我评论它时,它可以工作。
-
为什么不使用随数据增长的数组,比如 List?你的意思是一个数组列表?