如何定位列表中的每个第n个元素,但仅限于3

时间:2014-01-25 15:38:23

标签: java math

如何为此表达式编写公式:

boolean showAd = (position == 3 || position == 11 || position == 19 || position == 27 || position == 35 || position == 43|| position == 51);
        if (showAd) {.....

我尝试了position % 8 ==0,但这并没有产生与上面相同的序列

2 个答案:

答案 0 :(得分:2)

替换

position % 8 ==0

通过

position % 8 == 3

答案 1 :(得分:1)

该行

boolean showAd = (position == 3 || position == 11 ||
    position == 19 || position == 27 || position == 35 
    || position == 43|| position == 51);

将类似于

boolean showAd = (position - 3) % 8 == 0 // Note the parentheses

// (3 - 3) = 0 % 8 = 0
// (11 - 3) = 8 % 8 = 0
// (19 - 3) = 16 % 8 = 0
// (27 - 3) = 24 % 8 = 0
// ...

但是没有必要将布尔值存储在单独的变量中(除非您稍后使用它):

if ((position - 3) % 8 == 0) {
   ...
}