【问题标题】:Java Arrays increasingJava 数组增加
【发布时间】:2014-04-07 02:20:23
【问题描述】:

我需要帮助我的一种方法来延长数组。因此,如果数组是 ABC,我希望 void 方法使其成为 AABBCC。到目前为止,这是我的代码:

public void lengthen(){ 
    double[]t = new double[samples.length];

    for(int i = 0;i<samples.length;i++){
        t[i] = samples[i];
    }
    samples = new double[t.length*2];
    for(int i = 0; i < samples.length;i++){
        samples[(2*i)] = t[i];
        samples[(2*i)+1] = t[i];
    } 
}

【问题讨论】:

  • 所以?你测试过它是否有效吗?
  • 你的问题是?
  • 是的,我总是越界异常
  • @user3284325 正如@Jake 所说,您的第二个 for 循环从 0 到 1 小于 samples 的长度,这显然是错误的。这就是给你出界异常的原因。

标签: java arrays


【解决方案1】:

当您在循环体中填充两个数组元素时,您希望第二个数组只增加到最大值 i/2

【讨论】:

    【解决方案2】:

    您的问题是您的循环遍历 double-sized 数组的索引并使用它来索引 singly-sized 数组,因此您超出了-边界异常。

    这可以很简单地完成,例如:

    public void lengthen() {
        // Create new array, twice as many elements.
    
        double [] t = new double[samples.length * 2];
    
        // Transfers the elements, n -> 2n, 2n+1, n ranging from 0 to N-1 inclusive.
    
        for (int i = 0; i < samples.length; i++) {
            t[i*2]   = samples[i]; // 0->0, 1->2, 2->4, ..., (N-1)->(2N-2).
            t[i*2+1] = samples[i]; // 0->1, 1->3, 2->5, ..., (N-1)->(2N-1).
        }
    
        // Load into member variable.
    
        samples = t;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 2017-08-07
      • 1970-01-01
      • 2022-01-13
      • 2016-02-20
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多