• About Me
  • Java基礎教學
  • 部落格聯播

Java判斷式-流程判斷是與否

分類: Java, Java基礎入門, 教學 時間:2010/4/22 瀏覽:1,126 瀏覽數 — 留下回應

判斷式的使用方法在各種語言上其實都大同小異,不外乎是if else及switch或著是? : 三種,在使用上每個判斷式其後用左右的大刮號{ }夾著要執行的敘述句。以下簡單一下這種種判斷式的用法。

if else 判斷式

if (條件為true))

多行敘述句;;
else

條件為flase的執行敘述句;

或著單行敘述時我們可以使用以下方式

if (條件為true))
單行敘述句;
例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//hello.java
public class hello {
    public static void main(String args[])
    {
        int x =5;
        int y = 6;
        int z =3;
        if(x>y)
            System.out.println("x>y");
        else //執行else內的敘述句,輸出x<y
            System.out.println("x<y");
 
        System.out.println("----------------------------");
 
        if(x>z)//執行if內的敘述句,輸出x>z
        {
            System.out.println("第二例子");
            System.out.println("x>z");
        }
        else
        {
            System.out.println("第二例子");
            System.out.println("x<z");
        }
    }
}

答案是:

x<y
----------------------------

第二例子

x>z

switch判斷式

switch如果要用if else  來做也是可以,不過在執行速度上,跟程式的可看性上會比較不好。

使用方式如下:

switch (識別字)

case 等於某識別字1 : 敘述句;break

case 等於某識別字2 : 敘述句;break

‧‧‧

default: 敘述句;

  • 每一個case後面都需要加break做中斷,否則會繼續向下做判斷。
  • 識別字只可為基本型態,如果是物件只可用if else來做流程判斷。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//swtichSoruce.java
public class swtichSoruce {
    public static void main(String args[])
    {
        char x ='a';
        //答案是印
        //不是Z也不是X
        switch (x)
        {
            case 'z' : System.out.println("是Z");break;
            case 'x' :
                System.out.println("是X");
                break;
            default:
                System.out.println("不是Z也不是X");
        }
        System.out.println("-------------------------");
        int y = 5;
        //答案是印
        //是3
        switch(y)
        {
            case 5 : System.out.println("是5");break;
            case 3 : System.out.println("是3");break;
        }
        System.out.println("-------------------------");
        int z = 5;
        //答案是印
        //是5
        //是3
        switch(z)
        {
            case 6 : System.out.println("是6");
            case 5 : System.out.println("是5");
            case 3 : System.out.println("是3");
        }
 
    }
}

答案是:

不是Z也不是X

-------------------------

是5

-------------------------

是5

是3

? : 斷判式

這個斷判式在新手上可能比較少使用,不過對一般熟的人使用上到很常見,這跟if else基本上是一樣的方式,只是敘述句只能存在單敘述,而無法寫入多行敘述。

條件條件為true的敘述條件為flase的敘述

例子:

1
2
3
4
5
6
7
8
9
10
11
//a.java
public class a {
    public static void main(String args[])
    {
        int x =5;
        //答案印出
        //是5
        System.out.println((x==5)?"是5":"不是5");
 
    }
}

答案是:

是5

Related Posts Plugin for WordPress, Blogger...

留下您想說的話:

*