gpt4 book ai didi

java - 如何让 while 语句打印出每第三个数字?

转载 作者:行者123 更新时间:2023-12-01 06:28:39 24 4
gpt4 key购买 nike

如何让 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...

最佳答案

尝试:

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);
}

关于java - 如何让 while 语句打印出每第三个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com