简体   繁体   English

用于打印 3 的倍数的 while 循环

[英]a while loop for printing multiple of 3

Your program should print the following:您的程序应打印以下内容:

 0 3 6 9 12 15 18 loop ended!

This is my code.这是我的代码。 May I know why can't I do the desired output?我可以知道为什么我不能做所需的输出吗?

int i = 0;

while(i%3 == 0 && i < 20 ) {
    System.out.print(i);
    i++;
}

System.out.print("loop ended!");

You have a condition in your while loop that must be satisfied for the while loop to continue running.您的 while 循环中有一个条件,必须满足 while 循环才能继续运行。 When i increments to 1, the while loop condition fails and thus will stop running, so your program will only print 0. You instead should use an if statement inside the while loop with the mod condition:当 i 递增到 1 时,while 循环条件失败,因此将停止运行,因此您的程序将只打印 0。您应该在 while 循环中使用带有 mod 条件的 if 语句:

int i = 0;
while(i < 20) {
    if(i%3 == 0) {
        System.out.print(i + " ");
    }
    i++;
}
System.out.print("loop ended!");

i % 3 == 0 && i < 20 - this condition evaluates to false when the value of i becomes 1. So loop only executes once. i % 3 == 0 && i < 20 - 当i的值变为 1 时,此条件评估为false 。因此循环仅执行一次。

You just need i < 20 as a loop condition and in each iteration of the loop, just add 3 in i .您只需要i < 20作为循环条件,并且在循环的每次迭代中,只需在i添加 3 。

int i = 0;

while(i < 20) {
   System.out.print(i + " ");
   i += 3;
}

System.out.print("loop ended!");

Output:输出:

0 3 6 9 12 15 18 loop ended!
public static void main(String... args) {
    int i = 0;

    do {
        System.out.print(i + " ");
    } while ((i += 3) < 20);

    System.out.print("loop ended!");
}

I offer to simplify your code with usein for loop:我提议使用 usein for循环来简化您的代码:

public static void main(String... args) {
    for (int i = 0; i < 20; i += 3)
        System.out.print(i + " ");

    System.out.print("loop ended!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM