英文:
Checking multiples of a number using a switch statement
问题
对于一个Java编程作业,我需要使用if
/else
语句和switch
语句来判断一个数字n
是否为2
、3
、7
或9
的倍数。使用if
/else
很简单(例如 n % 7 == 0
),但我似乎无法弄清楚如何使用switch
语句实现这一点。
英文:
For a Java programming assignment, I am required to use both if
/else
and switch
statements to display if a number n
is a multiple of 2
, 3
, 7
or 9
. Using an if
/else
is easy (e.g. n % 7 == 0
), but I cannot seem to figure out how to implement this with a switch
statement.
答案1
得分: 1
这是我能够的方式:
int arr[] = {2, 3, 7, 9};
for (int number:arr) {
int input = 9;
int result = input % number;
switch (result) {
case 0:
System.out.println(input + " 是 " + number + " 的倍数");
break;
default:
System.out.println(input + " 不是 " + number + " 的倍数");
}
}
英文:
This is the way I can
int arr[] = {2, 3, 7, 9};
for (int number:arr) {
int input = 9;
int result = input % number;
switch (result) {
case 0:
System.out.println(input+" is multiple of " + number);
break;
default:
System.out.println(input+" is not multiple of " + number);
}
}
答案2
得分: 1
使用新的Java 14模式匹配语法的稍显荒谬的解决方案。
boolean isMultiple = switch (n % 2) {
case 0 -> true;
default -> switch (n % 3) {
case 0 -> true;
default -> switch (n % 7) {
case 0 -> true;
default -> false;
};
};
};
英文:
Mildly ridiculous solution using the new Java 14 pattern matching syntax.
boolean isMultiple = switch (n % 2) {
case 0 -> true;
default -> switch (n % 3) {
case 0 -> true;
default -> switch (n % 7) {
case 0 -> true;
default -> false;
};
};
};
答案3
得分: 0
请尝试这个。它简单地迭代嵌套的 switch 块,打印出相应的结果。
int[] candidates = { 10, 15, 19, 21, 6, 9 };
for (int candidate : candidates) {
System.out.printf("%d 可以被以下数整除:", candidate);
StringBuilder sb = new StringBuilder();
switch (candidate % 2) {
case 0:
sb.append(2).append(" ");
default:
switch (candidate % 3) {
case 0:
sb.append(3).append(" ");
default:
switch (candidate % 7) {
case 0:
sb.append(7).append(" ");
default:
switch (candidate % 9) {
case 0:
sb.append(9).append(" ");
default:
}
}
}
}
System.out.println(sb.length() > 0 ? sb.toString() :
"无法被以上数整除。");
}
输出结果:
10 可以被以下数整除:2
15 可以被以下数整除:3
19 无法被以上数整除。
21 可以被以下数整除:3 7
6 可以被以下数整除:2 3
9 可以被以下数整除:3 9
英文:
Try this. It simply iterates over nested switch blocks printing the appropriate results.
int[] candidates = { 10, 15, 19, 21, 6, 9 };
for (int candidate : candidates) {
System.out.printf("%d is divisible by ", candidate);
StringBuilder sb = new StringBuilder();
switch (candidate % 2) {
case 0:
sb.append(2).append(" ");
default:
switch (candidate % 3) {
case 0:
sb.append(3).append(" ");
default:
switch (candidate % 7) {
case 0:
sb.append(7).append(" ");
default:
switch (candidate % 9) {
case 0:
sb.append(9).append(" ");
default:
}
}
}
}
System.out.println(sb.length() > 0 ? sb.toString() :
"none of the divisors.");
}
Prints
10 is divisible by 2
15 is divisible by 3
19 is divisible by none of the divisors.
21 is divisible by 3 7
6 is divisible by 2 3
9 is divisible by 3 9
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论