【问题标题】:Copying specific elements of array to another array [duplicate]将数组的特定元素复制到另一个数组[重复]
【发布时间】:2018-02-17 17:09:02
【问题描述】:

我正在尝试复制帧数据的右侧部分。下面的图片可能很有用。数据为单数组形式。

我想获取数据框的单个数组右列。 我收到“线程“主”java.lang.ArrayIndexOutOfBoundsException: 1000 中的异常”。我不确定出了什么问题。

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1000

 public static void main(String args[]) {
    int height=10;
    int width = 100;
    int data[]= new int [height*width];
    int multipiler=0;
    int counter =1;
    int hwAssistWidth=5;
    int hwData[] = new int[hwAssistWidth*height];
    int countTheFrame = 0;
    int countTheFrame1 = 0;
    int sourceArray;

    for(int i=0; i<hwAssistWidth*height; i++){
            sourceArray = ((width-hwAssistWidth)+width*multipiler)+counter++;
            hwData[i] = data[sourceArray];


          if (counter==hwAssistWidth+1){
              counter =1;
              multipiler++;
              if(multipiler==height){
                  break;

              }

          }
    }

}

【问题讨论】:

  • 你调试你的程序了吗?
  • 是的,我做到了。请忽略数据数组中的值。
  • 因为你的索引超出了数组数据。
  • @MenaiAlaEddine,感谢您的评论。你能分享一下解决方法吗?

标签: java arrays sorting indexoutofboundsexception


【解决方案1】:

线

sourceArray = ((width-hwAssistWidth)+width*multipiler)+counter++;

在 for 循环的最后一次迭代中将 sourceArray 的值设置为 1000。然后您尝试访问数据数组的元素 1000

hwData[i] = data[sourceArray];

然而数据数组只有 1000 个元素

int height=10;
int width = 100;
int data[]= new int [height*width];

所以最大的索引只有 999,这就是你得到 ArrayIndexOutOfBounds 异常的原因。修复你的循环,使 sourceArray 的值永远不会大于 999。

【讨论】:

  • 谢谢@JoshuaNewHouse。它奏效了
  • 没问题。如果这回答了您的问题,那么您应该将其标记为已回答。
猜你喜欢
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2021-02-11
  • 1970-01-01
相关资源
最近更新 更多