简体   繁体   中英

Setting a max value for integer in android

In my code I implement myint++ on swipe up and myint-- on swipe down. But, I want to keep myint from exceeding certain values ie I don't want the value of myint to go above 10 or below 0. I cannot find how to accomplish this. Any help is appreciated :)

    int navX = navPref.getInt("navXPref", 5);
    int navY = navPref.getInt("navYPref", 5);

    switch (direction) {

       case SimpleGestureFilter.SWIPE_RIGHT : navX++;
                                            prefEditor.putInt("navXPref", navX);
                                            prefEditor.apply();
                                                break;
  case SimpleGestureFilter.SWIPE_LEFT : navX--;
                                            prefEditor.putInt("navXPref", navX);
                                            prefEditor.apply();
                                                 break;
  case SimpleGestureFilter.SWIPE_DOWN : navY--;
                                            prefEditor.putInt("navYPref", navY);
                                            prefEditor.apply();
                                                 break;
  case SimpleGestureFilter.SWIPE_UP : navY++;
                                        prefEditor.putInt("navYPref", navY);
                                        prefEditor.apply();
                                                 break;

  } 

Why not just do an if statement?

  case SimpleGestureFilter.SWIPE_DOWN : if(navY > 0)
                                            navY--;
                                        prefEditor.putInt("navYPref", navY);
                                        prefEditor.apply();
                                        break;
   case SimpleGestureFilter.SWIPE_UP : if(navY < 10)
                                           navY++;
                                       prefEditor.putInt("navYPref", navY);
                                       prefEditor.apply();
                                       break;

An alternative solution:

switch (direction) {
    case SimpleGestureFilter.SWIPE_RIGHT : navX++; break;
    case SimpleGestureFilter.SWIPE_LEFT : navX--; break;
    case SimpleGestureFilter.SWIPE_DOWN : navY--; break;
    case SimpleGestureFilter.SWIPE_UP : navY++; break;
} 
if (navX < 0) { navX = 0; }
if (navY < 0) { navY = 0; }
if (navX > 10) { navX = 10; }
if (navY > 10) { navY = 10; }
prefEditor.putInt("navXPref", navX);
prefEditor.apply();
prefEditor.putInt("navYPref", navY);
prefEditor.apply();

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