简体   繁体   中英

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.

I can print out the number of times three divides x like so:

  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!?

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

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. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void since you're printing instead of returning anything.

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

Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.

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.

public class MultiplesOfThree {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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