1. 程式人生 > 實用技巧 >第7節:Java switch、Java 條件語句【多測師_王sir】【軟體測試培訓】【www.duoceshi.cn】

第7節:Java switch、Java 條件語句【多測師_王sir】【軟體測試培訓】【www.duoceshi.cn】

1、if(){}小括號裡面只能是布林表示式,只能得到true或者false。 2、if理論上一直寫下去。 3、if鑲套最多不易超過三次。 4、if開頭可以用else結尾,也可以不用。 5、在多個if…else if…else if…語句中只會執行第一個滿足條件。 6、if…else if…else if…最多不易超過五次。
7、題目:求1~100之間,所有雙數之和,和說有單數之和。
/**
* 建立一個類
*/
publicclass Lesson {
    /**
     * 建立一個main方法
     */
    public static void main(String[] args) {
        //定義雙數和,單數和
        int i=0;
        int a=0;
        //用for迴圈寫出1到100的所有值
        for (int x=1;x<=100;x++){
            //用%摸分辨出是雙數或者單數
            if(x%2==0){
                i 
+=x; }else if (x%2!=0){ a +=x; } } System.out.println("雙數和:"+i); System.out.println("單數和:"+a); } } 8、在寫 swit case 語句時,如果未加break,後面的都會執行。 9、swit case 語句最後面的default分支不需要加break,default需要寫在最後一行,如果不在最後一行,需要加break。 10、 在確定固定值時候用swit case
語句塊,不確定值時候用if…else ifelse if…語句。(例如) publicclass Lesson2 { public static void main(String[] args) { String A="好"; switch (A){ case "好": System.out.println("男"); break; case "不好": System.out.println(
"女"); break; default: System.out.println("不存在"); } } } 11、 Case 必須是固定值或者字串。 12、 題目:隨機生成一個數1—9,這個數分四個等級獎勵 /** * 建立一個類 */ publicclass Ti1 { /** * 建立一個main方法 */ public static void main(String[] args) { //隨機生成一個數N(1-9) int a=(int)(Math.random()*9+1); //使用if...else if ...進行輸出a System.out.println(a); if(a>=8){ System.out.println("一等獎"); }else if (a>=5 && a<8){ System.out.println("二等獎"); }else if (a>=3 && a<5){ System.out.println("三等獎"); }else { System.out.println("安慰獎"); } } } 13、 題目:在控制檯輸出一個三位數,三位數的個十百位進行從大到小,從新組合。 importjava.util.Scanner; /** * 建立一個類 */ publicclass A2 { /** * 建立一個main方法 */ public static void main(String[] args) { //建立Scanner的一個物件 Scanner scanner=new Scanner(System.in); //控制檯上顯示:輸入任意三位數 System.out.println("輸入任意三位數"); //輸入的為字串是顯示"你的輸入有誤" if (scanner.hasNextInt() ) { //輸入這個三位數 int x = scanner.nextInt(); //個位數 int c = x % 10; //百位數 int a = x / 100; //十位數 int b = x / 10 % 10; //用if...else if...來比較三位數的大小,進行排序 if (a >= b && a >= c&& b >= c) { System.out.println((a * 100) +(b * 10) + c); } else if (a >= b && a>= c && c >= b) { System.out.println((a * 100) +(c * 10) + b); } else if (b >= a && b>= c && a >= c) { System.out.println((b * 100) +(a * 10) + c); } else if (b >= a && b>= c && c >= a) { System.out.println((b * 100) +(c * 10) + a); } else if (c >= a && c>= b && b >= a) { System.out.println((c * 100) +(b * 10) + a); } else if (c >= a && c>= b && a >= b) { System.out.println((c * 100) +(a * 10) + b); } } else { System.out.println("你的輸入有誤"); } } }