简体   繁体   English

向后遍历数组,减少计数器而不使用if语句。 模数的逆

[英]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. 当您单击下一个按钮时,mCurrent索引更新(++)并且Cursor指向列表中的下一个项目,而前一个按钮则相反。

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. 但我想知道是否有办法将previousButton代码重构为nextButton代码(简化它),通过消除if语句并替换为模数的倒数(即如果它存在)它仍然会起作用。

In each case the mCurrentIndex is reset when it reaches the end of the array. 在每种情况下,mCurrentIndex在到达数组末尾时都会重置。

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. 但我想知道是否有办法将previousButton代码重构为nextButton代码(简化它),通过消除if语句并替换为模数的倒数(即如果它存在)它仍然会起作用。

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);
  });

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

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