在不使用循环语句的情况下检查M到N数的条件

时间:2013-04-10 07:04:55

标签: java random

所以问题是:

用户必须指定2不 M (起点)和 N (终点)

程序必须使用以下条件检查M和N之间的所有数字:

  • 如果被3整除则打印“可被3整除”
  • 如果可被5分割,则“可被5整除”
  • 如果被3和5整除则打印“可被两个整除”

非常感谢java中的解决方案 只有允许循环检查条件

2 个答案:

答案 0 :(得分:0)

如果您想要递归

 void func(int M,int N)
{ 
if (M>N)
return;
 else
  {
   i=M;
    if(i%5==0 && i%3==0){

       system.out.println(i + "is divisible by both 3 and 5");

    }else if(i%5==0){

       system.out.println(i + "is divisible by  5");

    }else if(i%3==0){

       system.out.println(i + "is divisible by  3");

    }
    func(M++,N);
 }

}

答案 1 :(得分:0)

这是我对它的抨击,其过程称为Recursion

public class Main {

    private static int M, N;

    public static void main(String[] args) {
        M = 0; // min value
        N = 10; // max value
        noLoop(M); // begin the method
    }

    private static void noLoop(int currentNumber) {
        String resultMessage;

        if (currentNumber % 3 == 0) {
            resultMessage = currentNumber + " is divisible by 3.";
        } else {
            resultMessage = currentNumber + " is NOT divisible by 3.";
        }

        if (currentNumber % 5 == 0) {
            resultMessage = currentNumber + " is divisible by 5.";
        } else {
            resultMessage = currentNumber + " is NOT divisible by 5.";
        }

        if (currentNumber % 3 == 0 && currentNumber % 5 == 0) {
            resultMessage = currentNumber + " is divisible by BOTH 3 and 5.";
        }

        System.out.println(resultMessage);
        M++; // min value + 1
        if (M <= N) { // if min value == max value, STOP!
            noLoop(M);
        }
    }
}