Keep语句跳过 for、 while 或 do-while 循环的当前迭代。未标记的表单跳到最内层循环体的末尾,并计算控制循环的布尔表达式。下面的程序 ContinueDemo 逐步遍历 String,计算字母 p 的出现次数。如果当前字符不是一个 p,那么 keep 语句将跳过循环的其余部分,并继续执行到下一个字符。如果是 p,程序将增加字母数。
class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { // interested only in p's if (searchMe.charAt(i) != 'p') continue; // process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } }
下面是这个程序的输出:
Found 9 p's in the string.
若要更清楚地看到这种效果,请尝试删除 Continule语句并重新编译。当您再次运行该程序时,计数将是错误的,表示它找到了35个 p,而不是9个。
带标签的 Continule语句跳过用给定标签标记的外部循环的当前迭代。下面的示例程序 ContinueWithLabelDemo 使用嵌套循环在另一个字符串中搜索子字符串。需要两个嵌套循环: 一个循环遍历子字符串,另一个循环遍历正在搜索的字符串。下面的程序 ContinueWithLabelDemo 使用带标签的 keep 测试来跳过外部循环中的迭代。
class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test; } } foundIt = true; break test; } System.out.println(foundIt ? "Found it" : "Didn't find it"); } }
这是这个程序的输出。
Found it