用if和continue迭代

时间:2016-01-13 00:35:25

标签: java iterator

    public static void main(String[] args) {
    int b = 0, i;
    for (i = 0; i < 10; i++) {
        if (i % 5 <= 2) {
            continue;
        }
        b += ++i;
    }
    System.out.print(b);

为什么结果输出为13?不是28?

  • 迭代0,b = 0(5%0 = 0,继续;)
  • 迭代1,b = 0(5%1 = 1,继续;)
  • 迭代2,b = 0(5%2 = 2,继续;)
  • 迭代3,b = 4(5%3 = 3,b + = ++ i;)
  • 迭代4,b = 9(5%4 = 4,b + = ++ i;)
  • 迭代5,b = 9(5%5 = 0,继续;)
  • 迭代6,b = 9(5%6 = 1,继续;)
  • 迭代7,b = 9(5%7 = 2,继续;)
  • 迭代8,b = 18(5%8 = 3,b + = ++ i;)
  • 迭代9,b = 28(5%9 = 4,b + = ++ i;)

1 个答案:

答案 0 :(得分:1)

i开始49的循环迭代不会发生,因为++i添加到行i中的b += ++i; 。但这并不会阻止for循环增量操作i++的发生。这是真正的迭代序列:

  • 迭代0,i = 0,b = 0(0%5 = 0,继续;)
  • 迭代1,i = 1,b = 0(1%5 = 1,继续;)
  • 迭代2,i = 2,b = 0(2%5 = 2,继续;)
  • 迭代3,i = 3,b = 4(3%5 = 3,b + = ++ i;,我现在是4)
  • 迭代4,i = 5,b = 4(5%5 = 0,继续;)
  • 迭代5,i = 6,b = 4(6%5 = 1,继续;)
  • 迭代6,i = 7,b = 4(7%5 = 2,继续;)
  • 迭代7,i = 8,b = 13(8%5 = 3,b + = ++ i;,我现在是9)