继续使用for循环中的标签

时间:2016-10-14 21:13:46

标签: java for-loop continue

所以我正在Java Koans工作,而且我被困在第69位。这是代码:

@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?

提前致谢。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

<body> <!-- NAVIGATION BAR --> <nav role="navigation" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand text-center">Michael Adamski <br><span class="sub-brand">- Web Developer -</span></a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" id="navbar-list"> <ul class="nav navbar-nav navbar-right"> <li a href="home" class="active">Home</li> <li a href="#about">About</li> <li a href="portfolio">Portfolio</li> <li a href="Contact">Contact</li> </ul> </div> </div> </nav> <!-- End Navigation Bar --> <!-- Header --> <div class="jumbotron"> <div class="container"> <h1> This is my Page! </h1> <p> This is an example of what I can do with my newfound knowledge</p> </body>强制跳过第二个continue outerLabel;

虽然第二个for打算迭代6次,但它实际上只在for时迭代3次而在i==0时只迭代一次。

答案 1 :(得分:1)

  • 仅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