2015-11-01 99 views
-4

它返回3个A,但我不明白这是为什么?这是什么打印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"); 
     } 
    } 
} 
+5

东西,你大概忽略了什么:'我+ = 2' – Tunaki

+0

@Tunaki这是否意味着该阵列由两个会增加吗?所以1 + 2 = 3没有? –

+4

迭代仅查看元素0(3),2(2),4(3),6(1)和8(3)。其中只有3个是'3',所以'A'打印3次。 – Thevenin

回答

1

由于具有零为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 loop。另外,传入所需的值。像

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