Java中 break、continue 和 return三者之间的区别
生活随笔
收集整理的這篇文章主要介紹了
Java中 break、continue 和 return三者之间的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、Java break
可以直接強行退出當前的循環,忽略循環體中任何其他語句和循環條件測試
以下實例使用了 break 關鍵字來跳出當前循環:
public class Main {public static void main(String[] args) {int[] intary = { 99,12,22,34,45,67,5678,8990 };int no = 5678;int i = 0;boolean found = false;for ( ; i < intary.length; i++) {if (intary[i] == no) {found = true;break;}}if (found) {System.out.println(no + " 元素的索引位置在: " + i);} else {System.out.println(no + " 元素不在數組中");}} }以上代碼運行輸出結果為:
5678 元素的索引位置在: 6二、Java continue
continue語句用來結束當前循環,并進入下一次循環,但僅僅是這一次循環結束了,并不是所有循環結束了,后邊的循環依舊進行。
以下實例使用了 continue 關鍵字來跳過當前循環并開始下一次循環:
public class Main {public static void main(String[] args) {StringBuffer searchstr = new StringBuffer("hello how are you. ");int length = searchstr.length();int count = 0;for (int i = 0; i < length; i++) {if (searchstr.charAt(i) != 'h')continue;count++;searchstr.setCharAt(i, 'h');}System.out.println("發現 " + count + " 個 h 字符");System.out.println(searchstr);}以上代碼運行輸出結果為:
發現 2 個 h 字符 hello how are you.三、Java return
return用來返回方法指定類型值并結束函數執行,return 后面的語句不會被執行
以下實例使用了 return 關鍵字來返回方法指定類型值以及結束函數執行:
public static void main(String[] args) {int i;System.out.println("return語句之前" + getInfo());for (i = 0; i < 5; i++) {if (i == 3) {return;//無返回類型,用于方法的結束}System.out.println(String.format("i=%d", i));}//return 之后的語句將不會被執行System.out.println("return語句之后" + getInfo());}public static int getInfo() {return 1;//有返回類型,返回方法指定類型的返回值}以上代碼運行輸出結果為:
return語句之前1 i=0 i=1 i=2總結
以上是生活随笔為你收集整理的Java中 break、continue 和 return三者之间的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android各种报错问题汇总
- 下一篇: Android获取存储和打印输出Logc