1. 程式人生 > 其它 >Java基礎:流程控制

Java基礎:流程控制

Scanner物件

Scanner input = new Scanner(System.in);
String str = input.nextLine();
System.out.println("輸入的內容是"+str);
input.close(); //凡是io類的流如果不關閉會一直佔用資源,要養成及時關閉的習慣


  • next()

    • 一定要讀取到有效字元後才會結束輸入
    • 對有效字元前遇到的空白,next()方法會自動將其去掉
    • 只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符
    • 不能得到帶有空格的字串
  • nextline()

    • 以回車鍵為結束鍵,返回回車之前的所有字元
    • 可以獲得空白
//next()示例
import java.util.Scanner;
public class scanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); //輸入hello world!後回車
        if(scanner.hasNext()){
            String str = scanner.next();
            System.out.println(str);  // 輸出hello
            scanner.close();
        }
    }
}

//nextLine()示例
import java.util.Scanner;
public class scanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); //輸入hello world!後回車
        if(scanner.hasNextLine()){
            String str = scanner.nextLine();
            System.out.println(str); //輸出hello world!
            scanner.close();
        }
    }
}

switch多選擇結構

  • 變數型別可以是byte、short、int、char、String(java SE 7開始)
  • case標籤為字串常量或字面量
import com.sun.org.apache.bcel.internal.generic.SWITCH;
import java.util.Scanner;
public class scanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);  //輸入liu
        String xz = scanner.nextLine();
        switch (xz) {  //
            case ("liu"): {          
                System.out.println("no"); //輸出no
                break;   //沒有break語句,後面yes也會輸出
            }
            case ("zhu"): {
                System.out.println("yes");  
                break;
            }

        }
    }
}

//使用IDEA反編譯 java---class(位元組碼檔案)
/*
將out資料夾中的class檔案複製到str資料夾的對應java檔案同目錄下
在IDEA中開啟檢視反編譯碼
*/
  • println 輸出完會換行

  • print 輸出完不換行

for迴圈聯絡:列印三角形

public class forText {
    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();
        }
    }
}  //後兩步可以合併