循环后循环次数将在Java中迭代多少次?

时间:2015-03-17 12:18:03

标签: java arrays loops if-statement while-loop

int a = 1;
while (a < 20) {
    if ((++a % 3) == 0)
        System.out.println(“Divisible 3”);
    else if ((a++ % 3) > 0)
        System.out.println(“Not Divisible 3”);
    else break;
}

我不是一个更便宜的程序,我需要这个问题的解决方案。 循环后会循环多少次?

2 个答案:

答案 0 :(得分:0)

int count = 0;
int a = 1;
while (a < 20) {
   count++;
   if ((++a % 3) == 0)
      System.out.println("Divisible 3");
   else if ((a++ % 3) > 0)
      System.out.println("Not Divisible 3");
      else break;
   }
System.out.println("count = " + count);

输出:

Not Divisible 3
Not Divisible 3
Divisible 3
Not Divisible 3
Divisible 3
Not Divisible 3
Divisible 3
Not Divisible 3
Divisible 3
Not Divisible 3
Divisible 3
Not Divisible 3

count = 12

答案 1 :(得分:0)

结果如下:

循环运行12次

 3 Not Divisible 3
 5 Not Divisible 3
 6 Divisible 3
 8 Not Divisible 3
 9 Divisible 3
11 Not Divisible 3
12 Divisible 3
14 Not Divisible 3
15 Divisible 3
17 Not Divisible 3
18 Divisible 3
20 Not Divisible 3