【问题标题】:Insert a charcter in an array string periodically定期在数组字符串中插入一个字符
【发布时间】: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?你的意思是一个数组列表?

标签: java arrays string


【解决方案1】:

你的 for 循环中有一个错字 (i=i++),你应该总是增加 k 至少一次。这有效:

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++){
        withCommos[k]=points[i];
        insert=insert+1;
        if(insert==2 && k<withCommosSize-1){
            withCommos[k+1]=",";
            k++;
            insert=0;
        }
        k++;
    }
    return withCommos;
}

【讨论】:

    【解决方案2】:

    可能是这样的

    List<String> list = new ArrayList<String>();
    for(int i=0;i<points.length;i++)
                {
                    list.add(points[i]);
                    if(i==(points.length-1)) break;
                    list.add(",");
                }
    

    【讨论】:

      【解决方案3】:

      Unable to start activity ComponentInfojava.lang.ArrayIndexOutOfBoundsException:

      由于i=i++,您会收到此异常。检查这个link

      此语句不会增加i 的值,但您每次都会增加k 的值(使用if 或else)。由于i 没有增加您的for 循环将在无限循环中运行。一旦k 的值大于withCommosSize,您将得到ArrayIndexOutOfBoundsException。

      将 i=i++ 更改为 i++ 即可。

      【讨论】:

      • 谢谢,我做到了,现在可以运行了!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2011-08-02
      • 2015-02-11
      • 1970-01-01
      相关资源
      最近更新 更多