[英]Java several conditions with the help of 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!);
}
}
我認為
x % a == 0 && x % b == 0 && x % c == 0
等於
x%(a * b * c)== 0
UPDATE
乘法不正確,您需要使用LCM : x % lcm(a, b, c)
看一看 :
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!
我知道代碼看起來有些恐懼,但可以用於x
和num
任何值
這是使一名復合科學教授滿意的條件:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.