如何使每个第3个数字打印出一个while语句?

时间:2014-01-14 11:11:09

标签: java while-loop

如何使每个第3个数字打印出一个while语句?

我知道这会打印出0到100之间的数字:

package WhileStatement;

import java.util.Scanner;

public class WhileStatementOne {

        //See the Scanner packet for more info.
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args){
        countNumber();
    }
        //We can now call ' countNumber ' at any time in this code.
    private static void countNumber(){
        // This is the whilestatement.
        int i = 0;
        while(i <=100){
            System.out.println(i);
            i++;
        }
    }
}

但我怎样才能打印出来:

3
6
9
12
15
etc...

7 个答案:

答案 0 :(得分:11)

尝试:

int i = 1;
while (i++ <= 100){
    if ( i % 3 == 0 ) {
        System.out.println(i);
    }
}

或:

int i = 3;
while (i <= 100){
    System.out.println(i);
    i += 3;
}

甚至:

for (int i : new Range(3,100,3)) {
    System.out.println(i);
}

答案 1 :(得分:2)

增加3

private static void countNumber(){
    // This is the whilestatement.
    int i = 3;
    while(i <=100){
        System.out.println(i);
        i+=3;
    }

}

答案 2 :(得分:1)

    int i = 3;
    while(i <=100){
        System.out.println(i);
        i += 3;
    }

答案 3 :(得分:1)

IntStream一起使用:

IntStream.iterate(3, x -> x + 3).limit(100/3).forEach(System.out::println);

输出:

3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99

答案 4 :(得分:1)

这个循环不好。但不改变你的流量。只需添加一个条件来分析你想要的东西。

int i = 0;
    while (i <= 100) {
        if (i != 0 && i % 3 == 0)
            System.out.println(i);
        i++;
    }

答案 5 :(得分:0)

for (int i = 3; i <= 100; i+=3)
{
    System.out.println(i);
}

答案 6 :(得分:0)

public static void main(String[] args) {
    for(int i=3; i < 100; i = i + 3) {
        System.out.println(i);
    }
}