为什么我会得到重复的结果?

pdtvr36n  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(256)

我正在尝试编写一个代码,列出数组中的偶数,然后打印奇数之和:

public static void main(String[] args) {
    int[] numbers = {4, 643, 112, 9999, 69};
    int sumOdd = 0;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] % 2 == 0) {
            System.out.println(numbers[i]);
        }
    }
    for (int j = 0; j < numbers.length; j++) {
        if (numbers[j] % 2 != 0) {
            sumOdd = sumOdd + numbers[j];
        }
        System.out.println("SUMA " + sumOdd);
    }
}

但我的结果如下:

4
112
SUMA 0
SUMA 643
SUMA 643
SUMA 10642
SUMA 10711

你能指出哪里不对劲吗?这样我就能得出结果:

4
112
SUMA 10711

(全部在单独的行中)

g6ll5ycj

g6ll5ycj1#

只需移动 System.out.println("SUMA " + sumOdd); 跳出for循环

public static void main(String[] args) {
        int[] numbers = {4, 643, 112, 9999, 69};
        int sumOdd = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] % 2 == 0) {
                System.out.println(numbers[i]);
            }
        }
        for (int j = 0; j < numbers.length; j++) {
            if (numbers[j] % 2 != 0) {
                sumOdd = sumOdd + numbers[j];
            }

            }
        System.out.println("SUMA " + sumOdd);
    }

如注解中所述,您还可以通过添加else语句跳过第二个for循环,如:

public static void main(String[] args) {
    int[] numbers = { 4, 643, 112, 9999, 69 };
    int sumOdd = 0;
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] % 2 == 0) {
            System.out.println(numbers[i]);
        } else {
            sumOdd = sumOdd + numbers[i];
        }
    }
    System.out.println("SUMA " + sumOdd);
}

相关问题