4 選擇

4.1 if 敘述

    if (score >= 60)
        System.out.print("及格");

例題:Intsect3.java
        測試Intsect3

4.2 量值比較

關係運算子

    >
    >=
    <
    <=
    ==
    !=

浮點數比較

由於精確度有限,浮點數的計算可能產生捨入誤差(roundoff error),如
    double r = Math.sqrt(2);
    if(r *r ==2)System.out.println("sqrt(2) squared is 2");
    else System.out.println("sqrt(2) squared is " + r * r);
執行後的結果為
    sqrt(2) squared is 2.0000000000000004
因此,測試 abs(x-y) <= 0,使用
    Math.abs(x-y) <= EPSILON * Math.max(Math.abs(x), Math.abs(y));

字串比較

    if ( name.equals("Harry") ) ...
    if ( name.toUpperCase().equals("HARRY") ) ...
依字典的次序比較:
Java 所用的次序,數字在前,接著大寫字母,再接著小寫字母。
                   <        s 在 t 之前
    s.compareTo(t) == 0
                   >        s 在 t 之後
注意: 字串(或物件)的比較不用 "==" 。

4.3 輸入確認

例題:

  1. Check positive age ReadAge1.java
  2. Check integer age ReadAge2.java
說明:

4.4 if/else 敘述

    if (score >= 60)
        System.out.print("及格");
    else
        System.out.print("不及格");

例題:Intsect4.java
        測試Intsect4

4.5 Multiple Alternatives

    if (score >= 80)
        System.out.print("甲");
    else
      if (score >= 70)
          System.out.print("乙");
      else
        if (score >= 60)
            System.out.print("丙");
        else ...

例題:
  1. 與測試的次序無關 Coins6.java
  2. 與測試的次序有關 Richter.java

4.6 多層分支

例題:Tax.java

4.7 邏輯運算

boolean 型式

    int x =5;
    System.out.println(x < 10);

boolean 運算子

    and    &&
    or     ||
    not    !
例如,
    if (tday == bday && tmonth == bmonth)
       System.out.println("Happy Birthday!");

    if (tmonth > bmonth || (tmonth == bmonth && tday > bday))
       System.out.println("Too late to buy a gift");

例題:Birthday2.java

使用boolean 變數

假如測試的條件過於複雜,可利用boolean 變數予以簡化:
    boolean shipByAir = false;
    if (!country.equals("USA")) shipByAir = true;
    else if (state.equals("AK") || state.equals("HI"))
       shipByAir = true;
    if (shipByAir)
       shippingCharge = 20.00;
    else
       shippingCharge = 5.00;