我需要帮助了解for
循环为什么运行6次的逻辑。循环不应该在i = 4, j = 5
处停止吗?
public static boolean methodName(int[] hand)
{
int counter = 0;
for (int i = 0; i < hand.length-1; i++) {
for (int j = i+1; j < hand.length; j++) {
if (hand[i] == hand[j] && j != i) {
counter++;
System.out.println(counter);
}
}
}
if (counter == 4) {
return true;
}
return false;
} // end method
我插入了该行System.out.println(counter)
,以查看循环执行了多少次迭代。
输出如下:
Enter five ints.
Input 1: 2
Input 2: 2
Input 3: 2
Input 4: 2
Input 5: 3
1
2
3
4
5
6
答案 0 :(得分:0)
I=0,J=1, 2=2 counter = 1
I=0,J=2 2=2 counter = 2
I=0,J=3 2=2 counter = 3
I=0,J=4 2<>3 counter = 3 no print
I=1,J=2, 2=2 counter = 4
I=1,J=3, 2=2 counter = 5
I=1,J=4, 2<>3 counter = 5 no print
I=2,J=3, 2=2 counter = 6
I=3,J=4, 2<>3 counter = 6 no print