能被三整除

Divisible by three

我是编码方面的新手,并尝试完成一些开放的大学任务。也许你们可以伸出援手。我什至不知道如何开始这个任务, 是从 main 到方法中划分三个整数。示例 2, 10 我应该打印 3, 6, 9 或 2, 6 我应该打印 3, 6.

import java.util.Scanner;

public class divideByThree {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        divideByThree(2, 10);

    }
    public static void divideByThree(int start, int end) {

        while(true) {
            if (start % 3 == 0) {
                start++;
            }
            if (end % 3 == 0) {
                System.out.println(end);

            }
            System.out.println(start);
     }

    }
}
  1. 不要使用 while(true),因为它会创建一个无限循环,这会使您的程序变得复杂。
  2. 您需要在每次迭代中将start增加1,并在start值超过end时终止循环。
  3. 每当 start % 3 == 0 变为真时,打印 start

下面给出了一个示例代码,您可以使用它来理解上述要点。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter the start number: ");
        int start = reader.nextInt();
        System.out.print("Enter the end number: ");
        int end = reader.nextInt();
        divideByThree(start, end);
    }

    public static void divideByThree(int start, int end) {
        while (start <= end) {
            if (start % 3 == 0) {
                System.out.println(start);
            }
            start++;
        }
    }
}

样本运行:

Enter the start number: 3
Enter the end number: 9
3
6
9

下面关于divideByThree方法的实现怎么样?

  public static void divideByThree(int start, int end) {
        for(int i = start; i <= end; ++i){
        if(i%3==0){
        System.out.print(i+" ");
        }
        }
    }

递归方法

import java.util.Scanner;

public class DivideByThree {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int start = reader.nextInt();
        int end = reader.nextInt();
        divideByThree(start, end);
        reader.close();
    }

    public static void divideByThree(int start, int end) {
        if(start % 3 == 0) {
            System.out.println(start);
        }
        if( start <= end) {
            divideByThree(++start, end);
        }  
    }
}

while(true) 是一个无限循环(你会想避免的事情)。只有当你在其中某处添加一个 break 语句时,它才会停止,而你没有。 我认为这是您需要解决的问题。解决它的关键是简单地确保你的循环在某个点停止。你是怎么做到的?

True 是一个布尔值。只要指定的条件保持为真,while 循环就会一次又一次地运行,在您的情况下 - 它始终为真。您需要做的是将 while(true) 替换为 while(some condition that will be false at some point)。在您的特定情况下,while(start <= end) 似乎是合适的 - 只需确保在每次迭代时增加 start

另一种方法是使用 for 循环,即:

for (int i = start; i <= end; i++) {
   // your code
}

这种类型的循环负责说明循环应保持的条件 运行,还负责递增索引 i 以确保循环停止 运行 在某个时候。

我只会对您的代码做一些小改动,以便您能够快速理解。

public static void divideByThree(int start, int end) {

    while(start! =end) {
        if (start % 3 == 0) {
        System.out.println(start);
            start++;
        }
} 
}