Mik*_*ike 2 java arrays string boolean arraylist
我有一个方法,它接受一个字符串数组,并根据长度找到每个项目的平均值.我希望该方法根据offset的值删除数组中的前几个项目.
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;
}
Run Code Online (Sandbox Code Playgroud)
*注意:convert(); 将String []转换为double []
数组在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));
Run Code Online (Sandbox Code Playgroud)
输出:
[0.1, 0.2, 1.1, 1.2]
[1.1, 1.2]
Run Code Online (Sandbox Code Playgroud)