[英]Java several conditions with the help of for loop
I wonder if it is possible to have minimal code for this: 我想知道是否有可能为此提供最少的代码:
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!);
}
}
Have a look : 看一看 :
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!");
}
}
OUTPUT : 输出:
6 success!
I know the code is looking a little horrified but will work for any value of x
and num
我知道代码看起来有些恐惧,但可以用于x
和num
任何值
This is what you'd need to make a comp sci professor happy: 这是使一名复合科学教授满意的条件:
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!");
}
}
although note: (x % 1) is always 0. 尽管注意:(x%1)始终为0。
This is what you'd need to make me happy, according to my rule of "avoid nested loops": 根据我的“避免嵌套循环”规则,这就是让我高兴的条件:
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.