1. 程式人生 > 實用技巧 >Day03_流程控制

Day03_流程控制

Day03_流程控制

使用者互動Scanner

注意:每次使用完IO介面後都要關閉,防止一直佔用。

使用next()和nextLine()方法讀取輸入內容的區別:

import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
      //建立一個scanner物件,用於接收鍵盤資料
        Scanner scanner = new Scanner(System.in);
        System.out.print("用next方式輸入:");

        //判斷使用者有沒有輸入字串
        if(scanner.hasNext()){
            String str= scanner.next();
            System.out.println("輸入的內容為:"+str);
        }
        scanner.close();
    }
}

用next方式輸入:Hello World!
輸入的內容為:Hello

import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        //建立一個scanner物件,用於接收鍵盤資料
        Scanner scanner = new Scanner(System.in);
        System.out.print("用next方式輸入:");

        //判斷使用者有沒有輸入字串
        if (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            System.out.println("輸入的內容為:" + str);
        }
        scanner.close();
    }
}

用next方式輸入:Hello World!
輸入的內容為:Hello World!

原因是next()方法遇到空字元值時停止讀取,故只讀取了Hello就停止讀取了。nextLine()方法遇到回車符值時才停止讀取,故讀取到!後的回車鍵時才停止讀取。

判讀輸入的內容是否是int型別:scanner.hasNextInt()。判斷其他資料型別,將Int替換即可。

反編譯

將.class檔案放入IEDA中檢視,可以看原始碼。

while語句和doWhile

while()是不滿足條件時,就不執行。

doWhile()是即使不滿足條件,也會至少執行一次。

利用for迴圈列印三角形

public class Demo03 {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 5; j >= i; j--) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            for (int j = 1; j < i; j++) {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}