简体   繁体   中英

Iterate through an array in backwards direction, decreasing counter without using an if statement. Inverse of a modulus

I have an array and two buttons ( Next and Previous ). When you click on the next button the mCurrent index updates(++) and the Cursor points to the next item in the list, and the opposite for the previous button.

String[] fruits = {"Pineaple", "Orange", "Banana", "Apple"};
int mCurrentIndex = 0;

This is the event handlers for the buttons:

 nextButton.setOnClickListener(new View.OnClickListener() {

     @Override
     public void onClick(View view) {
         mCurrentIndex = (mCurrentIndex + 1) % fruits.length;
         updateFruit();
     }
 });



prevButton.setOnClickListener(new View.OnClickListener() {


 @Override
    public void onClick(View view) {
        mCurrentIndex = (mCurrentIndex - 1);
        if(mCurrentIndex < 0){
            mCurrentIndex = fruits.length - 1;
        }
        updateFruit();
    }

 });

The code is working normal. But I want to find out whether there could be a way to refactor the previousButton code to be like the nextButton code(Making it shorter), by eliminating the if statement and replacing with something like inverse of a modulus (that is if it exists) and it will still work the same.

In each case the mCurrentIndex is reset when it reaches the end of the array.

The code is working normal. But I want to find out whether there could be a way to refactor the previousButton code to be like the nextButton code(Making it shorter), by eliminating the if statement and replacing with something like inverse of a modulus (that is if it exists) and it will still work the same.

mCurrentIndex = (mCurrentIndex + fruits.length - 1) % fruits.length;

should do that

I think you can use

public void onClick(View view) {
    mCurrentIndex = (fruits.length + (mCurrentIndex - 1)) % fruits.length;
    updateFruit();
}

Use one method,

  updateFuit(int refIndex) {
       mCurrentIndex = (mCurrentIndex + refIndex) % fruits.length;
       // Do rest of the updates..
  }

For buttons,

 nextButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
        updateFruit(1);
   }
 });

 prevButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
        updateFruit(fruits.length - 1);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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