[英]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.