让我的头处于意大利面条模式。
下面是问题:
(检查数字)编写一个程序,提示用户输入一个整数,并检查该数字是否能被3和7整除,或者不能被3和7整除,或者只能被其中之一整除。以下是输入9、21和25的一些示例运行。
9可以被3或7整除,但不是两个21都能被3和7整除25不能被3或7整除
这就是我到目前为止所拥有的。我知道我错了,但不要认为我离解决这个问题太远了。
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 ");
}
}
}发布于 2014-12-17 01:54:39
我会执行每个模并将结果存储在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);
}发布于 2014-12-17 01:54:05
您不能使用异或运算符^或其他运算符||和&&来组合这样的两个条件,就像我们在英语中所做的那样。i是3的倍数,7不会转换为i % 3 == 0 && 7 == 0代码。您必须显式地写出每个单独的条件。
if ((i % 3 == 0) ^ (i % 7 == 0)) {和
else if ((i % 3 == 0) || (i % 7 == 0))和
if ((i % 3 == 0) && (i % 7 == 0)如果XOR运算符^中恰好有一个操作数为true,则它为true。因此,第一个条件表示“3或7,但不是两者都有”。接下来,我将在else if中使用&&示例,表示“既可以被3也可以被7整除”,else表示“既不能被3也不能被7整除”。
https://stackoverflow.com/questions/27510824
复制相似问题