简体   繁体   English

陷入while循环/索引越界异常

[英]Stuck in while loop / index out of bounds exception

I am trying to figure out when a step occurs. 我试图弄清楚何时发生了一个步骤。 So I have written a method called countSteps to do this. 所以我编写了一个名为countSteps的方法来执行此操作。 The problem with it is that I get stuck in it because with the while loop I keep getting new data and I don't think it ever returns back to onSensor. 它的问题是我陷入其中,因为使用while循环我不断获得新数据,我不认为它会返回onSensor。 I also get an error called indexoutofboundsexception: invalid index 2,size 2. 我还得到一个名为indexoutofboundsexception的错误:索引2无效,大小为2。

So my first question is are there any other ways to implement the method I have without the while loop? 所以我的第一个问题是有没有其他方法来实现我没有while循环的方法? Second is how can I fix the indexoutofboundsexception. 其次是我如何修复indexoutofboundsexception。 public class MainActivity extends Activity implements SensorEventListener { 公共类MainActivity扩展Activity实现SensorEventListener {

    private SensorManager mSensorManager;
    private Sensor mRotationVector;
    private Sensor mAccelerometer;
    private TextView mTextView4;
    private TextView mTextView5;
    private TextView mTextView6;
    private TextView mTextView7;
    private TextView mTextView8;
    float a, b, c, d, x, y, z, xyz;
    float[] retVals = new float[3];
    float avg = 10;
    float factor = (float) 1.15;
    ArrayList<Float> accelData = new ArrayList<Float>();
    public int peakCounter = 0;
    public int underAvgCounter = 0;

    public void countSteps() {
        int n = 0;
        float controlPoint = accelData.get(0);
        while (accelData.iterator().hasNext()) {
            if (accelData.get(n) != accelData.get(n + 1)) {
                if (accelData.get(n) > accelData.get(n + 1)) {
                    if (accelData.get(n) < controlPoint) {
                        n++;
                    } else {
                        if (accelData.get(n) < avg * factor) {
                            underAvgCounter++;
                        }
                        peakCounter++;
                        n++;
                    }
                } else {
                    controlPoint = accelData.get(n + 1);
                    n++;
                }
            } else {
                n++;
            }
            peakCounter -= underAvgCounter;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView4 = (TextView) findViewById(R.id.textView4);
        mTextView5 = (TextView) findViewById(R.id.textView5);
        mTextView6 = (TextView) findViewById(R.id.textView6);
        mTextView7 = (TextView) findViewById(R.id.textView7);
        mTextView8 = (TextView) findViewById(R.id.textView8);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        accelData.add((float) 0);
    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer,
                SensorManager.SENSOR_DELAY_GAME);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
            x = event.values[0];
            y = event.values[1];
            z = event.values[2];
            xyz = (float) Math.sqrt((x * x) + (y * y) + (z * z));
            accelData.add(xyz);
            mTextView7.setText("magnitude accel " + xyz);
            countSteps();
            mTextView8.setText("steps " + peakCounter);

    }
}
 while (accelData.iterator().hasNext()) {

Is always true if you have at least 1 element in collection. 如果集合中至少有1个元素,则始终为true。

  1. accelData.iterator() creates new iterator every time, accelData.iterator()每次都创建新的迭代器,
  2. accelData.iterator().hasNext() checks for the first element to be in collection every time accelData.iterator().hasNext()每次都检查要收集的第一个元素
  3. n++ is executed until end is reached and 执行n ++直到达到结束
  4. accelData.get(n + 1) throws IndexOutOfBoundsException accelData.get(n + 1)抛出IndexOutOfBoundsException

One of the things you can do is to use for loop. 你可以做的一件事是使用for循环。

 for (int n = 0; n < accelData.size() - 1; n++) {  // size-1 is used since you're accessing n+1 index
     if (accelData.get(n) != accelData.get(n + 1)) {
         if (accelData.get(n) > accelData.get(n + 1)) {
                if (accelData.get(n) >= controlPoint) {
                    if (accelData.get(n) < avg * factor) {
                        underAvgCounter++;
                    }
                    peakCounter++;                        
                }
        } else {
            controlPoint = accelData.get(n + 1);
        }
    } 
}
peakCounter -= underAvgCounter;
Iterator it = accelData.iterator();
while(it.hasNext()) {
  float elem = it.next();
  ...
}

With IndexOutOfBounds, the following code code snippets is an issue: 使用IndexOutOfBounds,以下代码代码段是一个问题:

accelData.get(n) and accelData.get(n + 1) accelData.get(n)和accelData.get(n + 1)

You are doing a check for iterator().hasNext(), but it doesnt guarantee the existence of n+1 element. 您正在检查iterator()。hasNext(),但它不保证存在n + 1个元素。

Infinite loop, I think is because you never used iterator().next() to traverse to the next element. 无限循环,我认为是因为你从未使用iterator()。next()来遍历下一个元素。 Please refer to a simple iterator code for better understanding. 请参阅一个简单的迭代器代码以便更好地理解。

And you can use any looping techniques like for, do while, while and advanced for loops in java, it doesnt matter. 并且您可以使用任何循环技术,例如for,do while,while和advanced for循环for java,这无关紧要。 All that matters is if you are doing it efficiently and its readable. 重要的是,如果你有效地做它并且它的可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM