流程式控制制語句的語法吧~
什麼是流程式控制制語句?
流程式控制制語句
在一個程序執行的過程中,各條語句的執行順序對程序的結果是有直接影響的。也就是說,程序的流程對運行結果有直接的影響。所以,我們必須清楚每條語句的執行流程。而且,很多時候我們要通過控制語句的執行順序來實現我們要完成的功能。
順序結構
public static void main(String[] args){
//順序執行,根據編寫的順序,從上到下運行
System.out.println(1);
System.out.println(2);
System.out.println(3);
}
還有哪些呢?
判斷語句1–if
if 語句第一種格式: if
if(關係表達式){
語句體;
}
執行流程
首先判斷關係表達式看其結果是 true還是false
如果是 true就執行語句體
如果是 false就不執行語句體

public static void main(String[] args){
System.out.println(“開始”);
// 定義兩個變數
int a = 10;
int b = 20;
//變數使用if判斷
if (a == b){
System.out.println(“a等於b”);
}
int c = 10;
if(a == c){
System.out.println(“a等於c”);
}
System.out.println(“結束”);
}
判斷語句2–if…else
if 語句第二種格式: if…else
執行流程
首先判斷關係表達式看其結果是 true還是false
如果是 true就執行語句體1
如果是 false就執行語句體2

public static void main(String[] args){
// 判斷給定的數據是奇數還是偶數
// 定義變數
int a = 1;
if(a % 2 == 0) {
System.out.println(“a是偶數”);
} else{
System.out.println(“a是奇數”);
}
System.out.println(“結束”);
}
判斷語句switch
switch(變數){
case 常量 :
語句塊
break;
//也可以有多個case
default :
語句塊
break;
}
循環語句for
for 循環語句格式:
for(初始化表達式①; 布爾表達式②; 步進表達式④){
循環體③
}
執行流程
執行順序:①②③④ >②③④>②③④…②不滿足為止。
①負責完成循環變數初始化
②負責判斷是否滿足循環條件,不滿足則跳出循環
③具體執行的語句
④循環後,循環條件所涉及變數的變化情況

public static void main(String[] args) {
//控制台輸出10次HelloWorld,不使用循環
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“HelloWorld”);
System.out.println(“‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐”);
//用循環改進,循環10次
//定義變數從0開始,循環條件為<10
for(int x = 0; x < 10; x++) {
System.out.println(“HelloWorld”+x);
}
}
循環語句while
while(布爾表達式){
//語句
}
循環語句do-while
do…while 循環是 while 循環的變種。該循環程序在初次運行時會首先執行一遍其中的代碼,然後當指定的條件為 true 時,它會繼續這個循環。所以可以這麼說,do…while 循環為執行至少一遍其中的代碼,即使條件為 false,因為其中的代碼執行後才會進行條件驗證。其語法結構是:
do {需執行的代碼 } while (變數 <= 結束值)
do {需執行的代碼 } while (變數 <= 結束值)
今天的知識蠻多的,大家加油喔,不懂的地方去上篇找小編的微信,幫你一起學java,我們明天再會~
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/230130.html
微信掃一掃
支付寶掃一掃