break语句
break语句有两种形式:标记和未标记。您在先前讨论中看到了未标记的switch语句。您还可以使用未标记的break语句终止for,while或do-while循环,如下面的 BreakDemo程序:
class BreakDemo {public static void main(String[] args) {int[] arrayOfInts ={ 32, 87, 3, 589,12, 1076, 2000,8, 622, 127 };int searchfor = 12;int i;boolean foundIt = false;for (i = 0; i < arrayOfInts.length; i++) {if (arrayOfInts[i] == searchfor) {foundIt = true;break;}}if (foundIt) {System.out.println("Found " + searchfor + " at index " + i);} else {System.out.println(searchfor + " not in the array");}}}
该程序在数组中搜索数字12。发现该值时,break语句终止for循环。然后,控制流在for循环后转移到该语句。该程序的输出为:
Found 12 at index 4
未标记的break语句终止最内层switch,for,while,或do-while语句,但标记的break终止一个外部语句。以下程序 BreakWithLabelDemo类似于先前的程序,但是在二维数组中使用嵌套for循环搜索值。找到该值后,带有标记的标记将break终止外for循环(标记为“search”):
class BreakWithLabelDemo {public static void main(String[] args) {int[][] arrayOfInts = {{ 32, 87, 3, 589 },{ 12, 1076, 2000, 8 },{ 622, 127, 77, 955 }};int searchfor = 12;int i;int j = 0;boolean foundIt = false;search:for (i = 0; i < arrayOfInts.length; i++) {for (j = 0; j < arrayOfInts[i].length;j++) {if (arrayOfInts[i][j] == searchfor) {foundIt = true;break search;}}}if (foundIt) {System.out.println("Found " + searchfor + " at " + i + ", " + j);} else {System.out.println(searchfor + " not in the array");}}}
这是程序的输出。
Found 12 at 1, 0
break语句终止带标签的语句;它不会将控制流转移到标签上。在标记(终止)的语句之后,控制流立即转移到该语句。
continue语句
continue语句跳过for,while或do-while循环的当前迭代。未标记的形式跳到最里面的循环主体的末尾,并评估控制该循环的boolean表达式。以下程序 ContinueDemo逐步执行字符串,计算字母“p”的出现。如果当前字符不是p,则该continue语句将跳过循环的其余部分,并继续执行下一个字符。如果它是 “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'sif (searchMe.charAt(i) != 'p')continue;// process p'snumPs++;}System.out.println("Found " + numPs + " p's in the string.");}}
这是该程序的输出:
Found 9 p's in the string.
若要更清楚地看到此效果,请尝试删除该continue语句并重新编译。当您再次运行该程序时,计数将是错误的,它找到的是35个p而不是9个。
带标签的continue语句跳过用给定标签标记的外部循环的当前迭代。下面的示例程序ContinueWithLabelDemo使用嵌套循环,在另一个字符串中搜索子字符串。需要两个嵌套循环:一个循环访问子字符串,另一个循环访问要搜索的字符串。以下程序 ContinueWithLabelDemo使用标记形式的Continue跳过外循环中的迭代。
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
return语句
分支语句的最后一个是return语句。return语句从当前方法退出,控制流返回到调用该方法的位置。return语句有两种形式:一种返回值,另一种不返回值。要返回值,只需将值(或计算值的表达式)放在关键字return之后。
return ++count;
返回值的数据类型必须与方法声明的返回值的类型匹配。声明方法void时,使用不返回值形式的return。
return;
“ 类和对象”课程将涵盖您需要了解的有关编写方法的所有内容。
