繁体   English   中英

为什么这会打印 3 A?

[英]Why does this print 3 A's?

它返回 3 A,但我不明白这是为什么?

这是我的代码:对于某个int[] array = {3, 3, 2, 1, 3, 2, 1, 3, 3};

public static void returns(int[]array){
    for (int i = 0; i < array.length; i+= 2) {
        if (array[i] == 3) {
            System.out.print("A");
        }
     }
}

因为i (和i+= 2 )的初始值为零,您只测试偶数索引,而其中只有 0 4 和 8 是 3。您可以使用类似

System.out.printf("%d A ", i);

而不是System.out.print("A"); 自己看看。

我得到

0 A 4 A 8 A

如果您想计算3 (s),我更喜欢for-each循环 此外,传入所需的值。 就像是

public static int count(int[] array, int value) {
    int count = 0;
    for (int i : array) {
        if (i == value) {
            count++;
        }
    }
    return count;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM