java流程控制實例代碼演示for、while、break、return等

#關注疫情,武漢加油#

感謝大家的轉發、收藏。需要源碼的留言聯繫小編免費領取即可!持續更新中...

1、 流程控制

程序在運行過程中會遇到各種各樣的情況,例如在上一篇圖文中( )通過關係操作符和邏輯操作符得出的結果就差強人意,會走向不同的程序分支上去,如何實現分支的選擇就要看流程控制了。例外程序還會出現不停執行某個語句,直到執行條件不成立為止的情況,也屬於流程控制。

Java處理流程控制的關鍵字和語句包含如下:for、return、break、 continue 、switch、 if-else、 while、 do-while。

下面看一下實例代碼演示效果:

java流程控制實例代碼演示for、while、break、return等

java流程控制代碼演示圖

附帶演示實例代碼如下:

<code>package com.part1;/** * Java流程控制測試類 * @author 紅魚程序員生活 * */public class ProcessControl {//顏色枚舉類型(後續篇章會詳細書寫)public enum Color {RED, YELLOW, BLUE, GREEN, BLACK}/** * 主方法 * @param args 輸入參數 */public static void main(String[] args) {testFor(); //for循環testReturn(2); //return testBreakAndContinue();//break continuetestSwitch(Color.RED);//switchtestIfElse(55);//if-elsetestWhileAndDoWhile();//while do-while}/** * 測試for關鍵字 */private static void testFor() {int[] arr = new int[10]; //整型一維數組//循環賦值for(int i = 0; i < 10; i++) {arr[i] = i;}//循環輸出for(int j : arr) {System.out.print(j + " ");}System.out.println("----------------------");}/** * 測試return * @param paramNum 輸入參數 */private static void testReturn(int paramNum) {if(paramNum == 1){System.out.println("測試testReturn");return;} else if (paramNum == 2) {try{System.out.println("testReturn try");return;} finally {System.out.println("testReturn finally");}}System.out.println("testReturn end");System.out.println("----------------------");}/** * 測試break和continue */private static void testBreakAndContinue() {int[] arr = new int[10];for (int i = 0; i < 10; i++) {arr[i] = i;}for(int j : arr) {if (j == 2) {continue;} if (j == 7) {break;}System.out.println(j + " ");}System.out.println("----------------------");}/** * 測試switch */private static void testSwitch(Color color) {switch(color) {case RED:System.out.println("switch color is " + Color.RED);break;case YELLOW:System.out.println("switch color is " + Color.YELLOW);break;case BLUE:System.out.println("swicht color is " + Color.BLUE);break;case GREEN:System.out.println("switch color is " + Color.GREEN);break;default:System.out.println("swicth color default is " + Color.BLACK);break;}System.out.println("----------------------");}private static void testIfElse(int num) {if (num > 9) {System.out.println("num > 9");}if (num < 100) {System.out.println("num < 100");} else {System.out.println(num >= 100);}System.out.println("----------------------");}private static void testWhileAndDoWhile() {int[] arr = new int[10];int i = 0;while(i < arr.length) {arr[i] = i;i++;}int j = 0;do {System.out.println(arr[j] + " ");j++;} while(j < arr.length);System.out.println("----------------------");}}/<code>

上述案例演示的不夠全面,小編也是一邊學習一邊編寫文章。大家一起學習,歡迎留言。在後面的圖文中會逐漸完善。

java流程控制實例代碼演示for、while、break、return等


分享到:


相關文章: