编程练习5

题目:输出1~100以内前5个可以被3整除的数。

思路:算一个能被3整除的数,输出直到5个后不再计算和输出。

代码:

 1 public class DivByThree {
2 public static void main(String[] args) {
3 int count = 0;
4
5 for (int i=1; i<100; i++)
6 {
7 if (i % 3 == 0)
8 {
9 System.out.println(i);
10 count++;
11 if (count == 5)
12 break;
13 }
14 }
15 }
16 }

结果:

3
6
9
12
15

也可以把最内层的if……break往外面提一层,与上一个if平级。

原文地址:https://www.cnblogs.com/qyddbear/p/2433860.html