2016-10-14 104 views
0

所以我的工作Java Koans和我卡上的数字69下面的代码:与标签继续在for循环中

@Koan 
public void forLoopContinueLabel() { 
    int count = 0; 
    outerLabel: 
    for (int i = 0; i < 6; i++) { 
     for (int j = 0; j < 6; j++) { 
      count++; 
      if (count > 2) { 
       continue outerLabel; 
      } 
     } 
     count += 10; 
    } 
    // What does continue with a label mean? 
    // What gets executed? Where does the program flow continue? 
    assertEquals(count, __); 
} 

assertEquals检查,如果答案是正确的 - 它发送Koans两争论,如果他们匹配你前进。例如,如果有人写了assertEquals(3 + 3, 6)这是正确的。

双下划线表示REPLACE ME。在Koans应用程序中,它说我需要用8代替下划线,但我不明白continue outerLabel的工作原理。

所以我的问题是:为什么计数8?

在此先感谢。任何帮助,将不胜感激。

+0

有一个在[官方教程]一些关于它(https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html):*标记continue语句跳过当前迭代一个外部循环标有给定的标签。* – UnholySheep

+0

你期望什么? – Yev

+2

对于更详细的解释:一旦你的count变量大于2(当'i'为0且'j'为2时会发生这种情况),'continue outerLabel'这行会一直跳到循环的开始(跳过'count + = 10'),然后迭代直到'i'变为6(计算迭代次数,您将看到'count'结束为值8) – UnholySheep

回答

0
  • 仅对于i为0的j为0,1,2
  • 对于其余的5我的唯一的j为0
  • 1 * 3 + 5 * 1 = 8

i j count 
= = ===== 
0 0 0  count++ 
     1  count++ 
    1 2  count++ 
    2 3  count++; continue outerLabel 
1 0 4  count++; continue outerLabel 
: : :  : 
5 0 8  count++; continue outerLabel 
1

continue outerLabel;强制跳过第二个for

虽然第二个for打算重复6次,但实际上它只在i==0i>0时重复3次。

+0

你的意思是“i == 0”的3次。 – Andreas

+0

谢谢。固定。 – Paulo