freeCodeCamp/guide/chinese/java/loops/continue-control-statement/index.md

1.4 KiB
Raw Blame History

title localeTitle
Continue Control Statement 继续控制声明

继续控制声明

continue语句使循环在继续之后跳过所有以下行,并跳转到下一次迭代的开始。在for循环中控制跳转到update语句whiledo while循环中,控制跳转到布尔表达式/条件。

for (int j = 0; j < 10; j++) 
 { 
    if (j == 5) 
    { 
        continue; 
    } 
    System.out.print (j + " "); 
 } 

除非等于5 ,否则将为每次迭代打印j的值。由于continue 将跳过print语句输出将是

0 1 2 3 4 6 7 8 9 

假设你想要在mississippi这个词中计算i的数量。在这里,您可以使用带有continue语句的循环,如下所示:

String searchWord = "mississippi"; 
 
 // max stores the length of the string 
 int max = searchWord.length(); 
 int numPs = 0; 
 
 for (int i = 0; i < max; i++) 
 { 
    // We only want to count i's - skip other letters 
    if (searchWord.charAt(i) != 'i') 
    { 
        continue; 
    } 
 
    // Increase count_i for each i encountered 
    numPs++; 
 } 
 
 System.out.println("numPs = " + numPs); 

:rocket: 运行代码

此外,您可以使用标签从嵌套集中选择特定循环以跳到下一次迭代。