1. 程式人生 > 其它 >常用類(2):Scanner類

常用類(2):Scanner類

常用類(2):Scanner類

Scanner類

1、通過jdk工具查出,Scanner類在util下,需要導包

2、鍵盤錄入工具:Scanner

注意:不能以Scanner作為class檔名
//導包
import java.util.Scanner;
public class ScannerDemo1 {
    public static void main(String[] args) {
        //建立鍵盤錄入物件
        Scanner sc = new Scanner(System.in);

        //鍵盤錄入一個int型別的資料
        //在API中寫出:public int nextInt()將輸入的下一個標記掃描為int
        int i = sc.nextInt();
        System.out.println(i);

        //鍵盤錄入一個字串
        String s1 = sc.next();
        System.out.println(s1);
    }
}

執行結果如下:

3、在API中,Scanner類中也有另外一個鍵盤錄入字串:public String nextLine()

sc.next()和sc.nextLine()兩個鍵盤錄入字串有什麼區別?

使用sc.next()
//導包
import java.util.Scanner;
public class ScannerDemo1 {
    public static void main(String[] args) {
        //建立鍵盤錄入物件
        Scanner sc = new Scanner(System.in);

        //先輸入一個整型再輸入一個字串
        int i = sc.nextInt();
        String s1 = sc.next();
        System.out.println(i);
        System.out.println(s1);
    }
}
        執行結果如下:
                    88
                    你好阿偉
                    88
                    你好阿偉

                    Process finished with exit code 0
使用sc.nextLine()
//導包
import java.util.Scanner;
public class ScannerDemo1 {
    public static void main(String[] args) {
        //建立鍵盤錄入物件
        Scanner sc = new Scanner(System.in);

        //先輸入一個整型再輸入一個字串
        int i = sc.nextInt();
        String s = sc.nextLine();
        System.out.println(i);
        System.out.println(s1);
    }
}
            執行結果如下:
                    88
                    88


                    Process finished with exit code 0
   /*
   當輸入88回車的時候,程式只會輸出88,然後執行停止,而且輸出結果多了一個空行
   原因:nextLine()可以讀取到特殊的符號,比如換行符;
   當我們輸入88,然後再回車,回車相當於換行符,被nextLine()讀取了,
   說明在String s = sc.nextLine();中,相當於把換行符傳給了s,
   然後輸出就會多了一個空行。
   */