Java for循环的几个条件

时间:2012-08-18 12:34:49

标签: java for-loop

我想知道是否可以使用最少的代码:

for (int x = 1; x < 10; x++){    
      /*I want to replace this condition with (x%number == 0) 
        instead of writing out condition for every number, but 
        it did not work with for (int number = 1; number <= 3; number++)
        in (x%number == 0), as it prints out every x and number 
      */
    if ((x%1) == 0 && (x%2) == 0 & (x%3) == 0){
       System.out.println(success!);
    }    
}

3 个答案:

答案 0 :(得分:3)

我认为 x % a == 0 && x % b == 0 && x % c == 0
相当于
x%(a * b * c)== 0

<强>更新
乘法不正确,您需要使用LCMx % lcm(a, b, c)

答案 1 :(得分:1)

看看:

for (int x = 1; x < 10; x++){
  boolean flag = false;
    for(int num = 1; num <= 3; num++){
       if ((x%num) == 0 ){
          flag = true;
       }else{
          flag = false;
          break;
       }
    }
    if(flag){
            System.out.println(x + " success!");
    }
}

输出:

6 success!

我知道代码看起来有些惊慌,但适用于xnum

的任何值

答案 2 :(得分:1)

这就是让你对comp sci教授感到高兴所需要的:

for (int x = 1; x < 10; x++){    
    boolean success = true;
    for (int number = 1; number <= 3; number++) {
        if ((x % number) != 0) {
            success = false;
        }
    }
    if (success) {
       System.out.println("success!");
    }    
}

虽然注意:(x%1)始终为0.

根据我的“避免嵌套循环”规则,这是你需要让我开心的事情:

for (int x = 1; x < 10; x++) {
    if (testNumber(x)) 
        System.out.println(x + " success!");
    }
}

private static boolean testNumber(int x) {
    for (int number = 1; number <= 3; number++) {
        if ((x % number) != 0) {
            return false;
        }
    }
    return true;
}