2011-06-20 288 views
2

我有一個方法需要一個字符串數組,並根據長度查找每個項目的平均值。我希望該方法根據偏移值刪除數組中的前幾個項目。如何從字符串數組中刪除前幾個項目?

public static double[] getMovingAverage(String[] priceList, int length, int offset){ 

    double[] newPriceList = convert(priceList); 

    int listLength = newPriceList.length; 
    int counter = 0; 
    double listsum; 
    double[] movingAverage = new double[listLength]; 

    try{ 
     for (int aa = 0; aa < listLength-1; aa++){ 
      listsum = 0; 
      for (int bb = 0; bb < length; bb++){ 
       counter = aa+bb; 

       listsum = listsum + newPriceList[counter]; 
      } 
      movingAverage[aa] = listsum/length; 
     } 
     if (offset>0){ 

         //remove first #offset# elements 

     } 
    }catch(Exception e){ 
     System.out.println(e); 
    } 
    return movingAverage; 
} 

* note:convert();將String []轉換爲double []

回答

6

陣列是固定長度在Java中。 (不能更改的陣列的長度。)

可以然而創建一個新的數組移除相當容易地在第一offset元素:

double[] movingAverage = { 0.1, 0.2, 1.1, 1.2 }; 
int offset = 2; 

// print before 
System.out.println(Arrays.toString(movingAverage)); 

// remove first offset elements 
movingAverage = Arrays.copyOfRange(movingAverage, offset, movingAverage.length); 

// print after 
System.out.println(Arrays.toString(movingAverage)); 

輸出:

[0.1, 0.2, 1.1, 1.2] 
[1.1, 1.2] 
2

從Java 6 API

公共靜態雙[] copyOfRange(雙[]原,從 INT, 的int)

複製的指定範圍 將指定數組轉換爲新數組。範圍(from)必須爲 的 初始索引位於0和original.length之間, (含)。將原始[來自] 的值放入 副本的初始元素(除非從== original.length或從==到)。來自 原始數組中的後續元素的值 被放置在 副本中的後續元素中。 (到)的範圍內,其中 必須大於或等於從所述的最終 索引, 可以是大於original.length,在這種情況下0D 被放置在其索引爲 越大副本的所有 元件大於或等於 original.length - from。返回的數組的長度爲 將從 - 。

參數:原 - 從 陣列,其範圍是從複製 - 該範圍的初始索引是 複製包容 - 該範圍的最後索引 被複制,排斥。 (此索引可以位於 陣列外部。)

返回:包含指定的範圍內的新的數組 從 原始陣列,截短的或 用零填充以獲得所需 長度

拋出: ArrayIndexOutOfBoundsException - 如果 從< 0或> original.length() - 如果從> 到NullPointerException - 如果原始 爲null時間: 1.6

+0

這是一個很好的答案;太糟糕了,在搜索「移位Java數組」時找不到它 - 也許這個評論可能有助於這方面的工作? – lre

2

而不是刪除項目,爲什麼不只是創建一個新的較小的大小列表作爲輸出,並始終使用索引偏移作爲索引呢?

+0

是的。初始化aa以在您處理時抵消。 – Robin

1

您不能顯式從數組中刪除,但可以使用其他數據結構(如ArrayList)來累積結果。不過,就你而言,你可能只是想改變代碼來正確調整數組的大小,即。

double[] movingAverage = new double[listLength-offset]; 

for (int aa = 0; aa < listLength-offset; aa++){ 
+0

如果你想這樣做,你需要從_offset_開始你的for循環,而不是0,你需要遍歷第一個偏移量元素來計算它們的總和,否則你的運行平均值的計算將是不正確的 – Asaf