保持循环运行以检查多个条件 - Java

Kut*_*tam 3 java loops

我有一个整数的数组.我想迭代它们来检查它是否可以被2,3,5整除.目前我的代码只运行一次.

所以说如果我在列表中有6个.它只返回"6可被2整除",它应该是"6可以被2和3整除"

那么我该如何使代码更优雅.有没有办法编写代码而无需定义喜欢if (number % 2 == 0) && (number % 3 == 0)...或必须以这种方式完成?每次定义每个条件.

这是我的代码

public class checkingDivisibility {
    public static void main(String[] args) {
        int list[] = {1, 2, 3, 6, 8, 10, 12, 14, 15, 17, 19, 21};
        for (int x : list) {
            if (x % 2 == 0) {
                System.out.println(x + "div by 2 possible");
            } else if (x % 3 == 0) {
                System.out.println(x + "div by 3 possible");
            } else if (x % 5 == 0) {
                System.out.println(x + "div by 5 possible");
            }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 7

你有一个else ifif,这意味着,在未来if,如果第一个是条件时才计算false.这不是你想要的.

你想要的是,应该检查每个条件.因此,您不需要else if语句,只需要独立if的语句.试试这个..

public class checkingDivisibility {
    public static void main(String[] args) {
        int list[] = {1, 2, 3, 6, 8, 10, 12, 14, 15, 17, 19, 21};
        for (int x : list) {
            if (x % 2 == 0) {
                System.out.println(x + "div by 2 possible");
            } 
            if (x % 3 == 0) {
                System.out.println(x + "div by 3 possible");
            }  
            if (x % 5 == 0) {
                System.out.println(x + "div by 5 possible");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 添加解释对OP更有帮助. (3认同)