1. 程式人生 > >判斷語句之if..else if...else

判斷語句之if..else if...else

src nbsp 技術 pri sta void ash true img

判斷語句之if..else if...else

  • if語句第三種格式:if..else if...else

格式:

技術分享圖片

執行流程

首先判斷關系表達式1看其結果是true還是false

如果是true就執行語句體1

如果是false就繼續判斷關系表達式2看其結果是true還是false

如果是true就執行語句體2

如果是false就繼續判斷關系表達式…看其結果是true還是false

如果沒有任何關系表達式為true,就執行語句體n+1。

代碼舉例:

public class Demo04IfElseExt {
    public
static void main(String[] args) { /*x和y的關系滿足如下: x>=3 y = 2x + 1; ‐1<=x<3 y = 2x; x<=‐1 y = 2x – 1; 根據給定的x的值,計算出y的值並輸出。 */ int x = 15; int y; if (x >= 3) { y = 2 * x + 1; } else
if (x >= -1 && x < 3) { y = 2 * x; } else { y = 2 * x - 1; } System.out.println("y的值是:" + y); } }

執行結果:

技術分享圖片

if..else if...else執行流程如下圖所示:

技術分享圖片

判斷語句之if..else if...else