简体   繁体   English

Java:创建方法以打印1到n之间的3的所有倍数吗?

[英]Java: Create method to print all multiples of 3 between 1 and n?

So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three. 因此,问题是要求创建一个方法,该方法将整数x作为参数并打印出0-> x的所有整数,该整数是3的倍数。

I can print out the number of times three divides x like so: 我可以这样打印出三除x的次数:

  public int Threes(int x){

    int i = 0;
    for(int counter = 1; counter <= x; counter++){
        if (counter % 3 ==0){
            i ++;
        }

    }
        return i;

but I'm not sure how to print out each multiple of 3!? 但我不确定如何打印3的每一个倍数!?

for(int counter = 1; counter <= x; counter++){
    if (counter % 3 ==0){
        System.out.println(counter);
    }

}

An even quicker approach would be to increment by 3 更快的方法是增加3

public void Threes(int x) {
    for (int counter = 3; counter <= x; counter = counter + 3) {
        System.out.println(counter);
    }
}

This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. 该循环将直接跳到3的倍数,而不是对每个数字进行计数,而不必为每次迭代进行模检查。 Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. 因为我们知道1和2不是3的倍数,所以我们在循环开始时就跳到3。 If the input happens to be less than 3, then nothing will be printed. 如果输入恰好小于3,则不会打印任何内容。 Also, the function should be void since you're printing instead of returning anything. 另外,该函数应该为void因为您要打印而不返回任何内容。

(Your title says 1 to n , but your question says 0 to n , so if you actually need from 0 to n , then change the declaration of counter to int counter = 0; ) (您的标题是1 to n ,但您的问题是0 to n ,因此,如果您实际上需要从0 to n ,则将counter的声明更改为int counter = 0;

Jason Aller wow that was so simple and elegant. 杰森·艾勒(Jason Aller)哇,简直如此优雅。 This one builds on it by counting down from 300 to 3, by 3's. 这个数字的基础是从300减到3,再减3。

public class byThrees {

public static void main(String[] args) {
    for (int t = 100; t >= 0; t--) {
        System.out.println(t*3); 

Best practice using the For-loop in Java. 在Java中使用For循环的最佳实践。

public class MultiplesOfThree {

    public static void main(String []args){
        for (int m = 1; m<=12; m++){
            System.out.println(m*3);
        }  
    }
}

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

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