我是java的新手,我发现自己陷入了一个难题。我解决问题的逻辑是正确的,但是我的逻辑运算符没有按照我期望的方式工作。下面是我写的程序:
public class idgaf {
public static void main(String[] args) {
int n=25;
for(int i=1;i<=n;i++){
if((i%7!=0)||(i%2!=0)){
System.out.print(i+" ");
}
}
}输出:1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19 20 21 22 23 24 25
我希望OR运算符执行它的操作,并且不显示7和2的倍数,但是,删除的唯一数字是14,这是7和2的倍数。我用and运算符尝试了相同的代码,并给出了正确的输出。
带AND运算符的输出:1 3 5 9 11 13 15 17 19 23 25
看起来好像AND运算符正在工作,而我期望OR运算符也能工作,反之亦然。有人能解释一下这是怎么回事吗?
发布于 2018-07-31 22:23:20
检查一下你的状况。它应该是:
if((i%7 != 0) && (i%2 != 0)){ .....i%7!=0 //不能被7整除
i%2!=0 //不能被2整除
使用AND将它们结合起来,您将获得正确的结果
发布于 2018-07-31 22:24:21
正确的版本应该是
public class idgaf {
public static void main(String[] args) {
int n = 25;
for (int i = 1; i <= n; i++) {
// here are two adjustments, && instead of || and % 2 != 0 (not 10)
if ((i % 7 != 0) && (i % 2 != 0)) {
System.out.print(i + " ");
}
}
}
}发布于 2018-07-31 22:38:21
尝试一些新的东西?
使用Java8的代码类似于下面的代码,它只返回满足您需求的顶级k整数:
public static void main(String... args) {
System.out.println(getTopK(10));
}
private static List<Integer> getTopK(int k) {
return IntStream.range(0, Integer.MAX_VALUE)
.filter(i -> i % 7 != 0 && i % 2 != 0)
.limit(k).boxed()
.collect(Collectors.toList());
}如果为k = 10,则输出为:
[1, 3, 5, 9, 11, 13, 15, 17, 19, 23]https://stackoverflow.com/questions/51615599
复制相似问题