Java 检查数字是否可以被 3 和 7 整除,或者都不能被它们整除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27510824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether the number is divisible by both 3 and 7, or by neither of them
提问by Sam777
Got my head in spaghetti mode.
我的头进入意大利面模式。
Here is the question:
这是问题:
(Check a number) Write a program that prompts the user to enter an integer and checks whether the number is divisible by both 3 and 7, or by neither of them, or by just one of them. Here are some sample runs for inputs, 9,21, and 25.
(检查一个数字)编写一个程序,提示用户输入一个整数,并检查该数字是否可以被 3 和 7 整除,或者不能被 3 和 7 整除,或者只能被 3 和 7 整除。以下是输入 9,21 和 25 的一些示例运行。
9 is divisible by 3 or 7, but not both 21 is divisible by both 3 and 7 25 is not divisible by either 3 or 7/
9 能被 3 或 7 整除,但不能同时被 3 和 7 整除 21 不能被 3 或 7 整除/
This is what I have so far. I know I'm wrong but do not think I am too far from solving the question.
这是我到目前为止。我知道我错了,但不要认为我离解决问题太远了。
public class Quest12 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int i = scan.nextInt();
if (i % 3 == 0 ^ 7 == 0) {
System.out.println(i + " is divisible by 3 or 7. ");
}
else if (i % 3 == 0 || 7 == 0)
{
System.out.println(i + " is divisble by either 3 or 7. but not both ");
}
if (i % 3 == 0 && 7 == 0)
{
System.out.println(i + " is divisble by both 3 and 7 ");
}
}
}
采纳答案by Elliott Frisch
I would perform each modulus and store the result(s) in boolean
variables. Like,
我会执行每个模数并将结果存储在boolean
变量中。喜欢,
boolean mod3 = i % 3 == 0;
boolean mod7 = i % 7 == 0;
if (mod3 && mod7) {
System.out.printf("%d is divisible by 3 and 7.%n", i);
} else if (mod3 || mod7) {
System.out.printf("%d is divisible by 3 or 7 (but not both).%n", i);
} else {
System.out.printf("%d is not divisible by 3 or 7.%n", i);
}
回答by rgettman
You cannot use the XOR operator ^
or the other operators ||
and &&
to combine 2 conditions like that, like we would in English. i
is a multiple of 3 and 7 is not translated to code as i % 3 == 0 && 7 == 0
. You must write out each separate condition explicitly.
不能使用XOR运算符^
或其他运营商||
和&&
2个条件结合起来一样,像我们将以英文。 i
是 3 的倍数,7 不会被转换为代码i % 3 == 0 && 7 == 0
。您必须明确写出每个单独的条件。
if ((i % 3 == 0) ^ (i % 7 == 0)) {
and
和
else if ((i % 3 == 0) || (i % 7 == 0))
and
和
if ((i % 3 == 0) && (i % 7 == 0)
The XOR operator ^
is true
if exactly one of its operands is true
. So, the first condition represents "either 3 or 7 but not both". Next, I would do the &&
case in the else if
, for "divisible by both 3 and 7", with an else
for "divisible by neither 3 nor 7".
XOR 运算符^
是,true
如果其操作数中的一个正好是true
。因此,第一个条件表示“3 或 7,但不能同时存在”。接下来,我将&&
在else if
, 为“可被 3 和 7 整除”中进行处理,而else
对于“既不能被 3 也不能被 7 整除”。