It returns 3 A's but I don't see why that is?
Here is my code: for a certain 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");
}
}
}
Because with an initial value of zero for i
(and i+= 2
) you are only testing the even indices, and of those only 0 4 and 8 are 3. You could use something like
System.out.printf("%d A ", i);
Instead of System.out.print("A");
to see for yourself.
I get
0 A 4 A 8 A
If you wanted to count the 3
(s), I'd prefer a for-each
loop . Also, pass in the desired value. Something like
public static int count(int[] array, int value) {
int count = 0;
for (int i : array) {
if (i == value) {
count++;
}
}
return count;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.