0

我正在尝试实现 Tom Nichols 的低通滤波器。我的方法是这样的,但我一直得到一个越界异常,即使我已经提防它:

private float  filterValue(LinkedList<Float> listOfItems)
    {
        final float ALPHA = 0.2f;
        float filtered;

        int marker = listOfItems.size();

        if (listOfItems.size()>2)
             marker = listOfItems.size() - 1;

        float current = listOfItems.pollLast();
        float previous = listOfItems.get(marker); <<-- line 282

        filtered = (float) previous + ALPHA*(current - previous);

        return filtered;


    }

错误日志:

12-16 15:54:51.148: E/AndroidRuntime(2055): FATAL EXCEPTION: main
12-16 15:54:51.148: E/AndroidRuntime(2055): java.lang.IndexOutOfBoundsException
12-16 15:54:51.148: E/AndroidRuntime(2055):     at      java.util.LinkedList.get(LinkedList.java:519)
 12-16 15:54:51.148: E/AndroidRuntime(2055):    at se.macke.velocitysensor.SensorActivity$MySensorEventListener.filterValue(SensorActivity.java:282)
 12-16 15:54:51.148: E/AndroidRuntime(2055):    at se.macke.velocitysensor.SensorActivity$MySensorEventListener.getAccelerometer(SensorActivity.java:249)
12-16 15:54:51.148: E/AndroidRuntime(2055):     at se.macke.velocitysensor.SensorActivity$MySensorEventListener.onSensorChanged(SensorActivity.java:231)
12-16 15:54:51.148: E/AndroidRuntime(2055):     at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
12-16 15:54:51.148: E/AndroidRuntime(2055):     at android.os.Handler.dispatchMessage(Handler.java:99)

建议,请。

/米

4

2 回答 2

3
if (listOfItems.size()<2)
    marker = listOfItems.size() - 1;

如果listOfItems.size()为零,那么 varmarker将是 -1 导致IndexOutOfBoundsException.

你应该把下限> 0

if (listOfItems.size()>0 && listOfItems.size()<2)
    marker = listOfItems.size() - 1;
于 2012-12-16T15:23:27.903 回答
2

Size 返回列表的实际大小,它不是零索引的。get 方法从使用从零开始的索引的列表中检索项目。守卫条件并不能阻止这个问题。

int marker = listOfItems.size();  //assume size = 3,
if (listOfItems.size()<2)   //condition is not met.
    marker = listOfItems.size() - 1;

float previous = listOfItems.get(marker); //attempts to access non-existent index of 3

使固定

private float  filterValue(LinkedList<Float> listOfItems)
{
    final float ALPHA = 0.2f;
    float filtered;

    int marker = listOfItems.size();

    if (listOfItems.size() > 0){

        marker = listOfItems.size() - 1;

        float current = listOfItems.pollLast();
        float previous = listOfItems.get(marker); <<-- line 282

        filtered = (float) previous + ALPHA*(current - previous);
    }
    return filtered;
}
于 2012-12-16T15:23:10.737 回答