循環語句

什麼是循環:舉例就是相同的事情重複做,例如操場跑圈跑圈,跑十圈就是循環了10次,例如吃包子,吃了10個包子就是循環了10次。


循環是有兩種的,一種是條件循環例如循環10次,百次,千次等等,還有一種是死循環無限循環不會停止。


嵌套循環,外循環控制的是行,內循環控制的是列。


import java.util.Scanner;

public class T6 {

    public static void main(String[] args) {
        for (int i = 1; i <=4 ; i++) {
            System.out.println();//共有4行從1開始
            for (int j = 1; j <=i ; j++) {
                System.out.print("*");//內控制列
            }
        }
    }
}


循環常用的是while循環和for循環,如果知道循環次數的話就用for,如果不知到次數就用while循環。

循環當中有兩個關鍵字:break 跳出最近循環(終止最近操作的循環

                                     continue 停止最近的本次循環 進行下次循環


import java.util.Scanner;

public class T6 {//continue 舉例
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            System.out.println();
            for (int j = 1; j <= i; j++) {
                if (i== 1) {
                    continue;//跳過了第一行
                } else {
                    System.out.print("*");
                }
            }
        }
    }
}


import java.util.Scanner;

public class T6 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a = input.nextInt();
        while (true) {
            if (a == 1) {
                break;
            }
            System.out.println("請輸入您的幸運數字");//如果不是1 他就會一直循環
        }
    }
}


關於while循環不知道次數的代碼應用舉例


import java.util.Scanner;

public class T6 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int yb = 0;
        int dn = 0;
        int hu = 0;
        while (true) {
            System.out.println("歡迎您來的無敵酒店");
            System.out.println("1、一般房150");
            System.out.println("2、電腦房250");
            System.out.println("3、豪華房350");
            System.out.println("請選擇您需要的房間");
            System.out.println("結束服務請選4");
            int i = input.nextInt();
            if (i == 1) {
                yb++;
            }
            if (i == 2) {
                dn++;
            }
            if (i == 3) {
                hu++;
            } else {
                System.out.println("請選擇正確的房間");
            }
            if (i == 4) {
                int j = (yb * 150) + (dn *250) + (hu * 350);
                int b = yb + dn + hu;
                System.out.println("您共消費" + j + "元");
                System.out.println("您共定製了" + b + "間房");
                break;
            }
        }
    }
}

debug 就是斷點測試:我們可以一步一步的執行 查看它的執行過程

                                  1.出現錯誤 找不到出錯的地方 可以使用Debug 一步步執行

                                  2.看不懂代碼 也可以使用 Debug一步步去查看它的運行

                                  3.也可以使用debug觀察程序情況


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章