0

トム・ニコルズのローパスフィルターを実装しようとしています。私のアプローチはこのようなものでしたが、それを防いだとしても、常に範囲外の例外が発生します。

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)

提案をお願いします。

/ M

4

2 に答える 2

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

What if listOfItems.size() is zero then var marker would be -1 which cause IndexOutOfBoundsException.

you should put lower bound > 0.

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

Size returns the actual size of the list, it is not zero indexed. The get method retrieves an item from the list which uses a zero based index. The guard condition does not prevent this issue.

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

Fix

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 に答える