1、Scanner類概述
JDK5以后用於獲取用戶的鍵盤輸入,一個可以使用正則表達式來解析基本類型和字符串的簡單文本掃描器。Scanner 使用分隔符模式將其輸入分解為標記,默認情況下該分隔符模式與空白匹配。然后可以使用不同的 next 方法將得到的標記轉換為不同類型的值。
2、現在使用的構造方法
public Scanner(InputStream source)
3、Scanner類的成員方法
1)基本格式
hasNextXxx() 判斷是否還有下一個輸入項,其中Xxx可以是Int,Double等。如果需要判斷是否包含下一個字符串,則可以省略Xxx。
nextXxx() 獲取下一個輸入項。Xxx的含義和上個方法中的Xxx相同。
2)默認情況下,Scanner使用空格,回車等作為分隔符



3)舉例:用int類型的方法舉例
public boolean hasNextInt()
public int nextInt()
public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); // 獲取數據,先判斷輸入的數據是否與接收的變量的類型匹配 if (sc.hasNextInt()) { int x = sc.nextInt(); System.out.println("x:" + x); } else { System.out.println("你輸入的數據有誤"); } } }
4)分析以下兩個方法的組合使用:
public int nextInt()
public String nextLine()
如果先獲取一個數值,再獲取一個字符串,會出現問題。主要原因:就是那個換行符號的問題。
問題解決:
A:先獲取一個數值后,在創建一個新的鍵盤錄入對象獲取字符串。
B:把所有的數據都先按照字符串獲取,然后要什么,你就對應的轉換為什么。
public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); // 獲取兩個int類型的值 int a1 = sc.nextInt(); int b1 = sc.nextInt(); System.out.println("a:" + a1 + ",b:" + b1); System.out.println("-------------------"); // 獲取兩個String類型的值 String s1 = sc.nextLine(); String s2 = sc.nextLine(); System.out.println("s1:" + s1 + ",s2:" + s2); System.out.println("-------------------"); // 先獲取一個字符串,在獲取一個int值 String s3 = sc.nextLine(); int b2 = sc.nextInt(); System.out.println("s1:" + s3 + ",b:" + b2); System.out.println("-------------------"); // 先獲取一個int值,在獲取一個字符串,數據獲取有誤 int a2 = sc.nextInt(); String s4 = sc.nextLine(); System.out.println("a:" + a2 + ",s2:" + s4); System.out.println("-------------------"); //解決方法:定義兩個Scanner對象,分別獲取兩次數據 int a = sc.nextInt(); Scanner sc2 = new Scanner(System.in); String s = sc2.nextLine(); System.out.println("a:" + a + ",s:" + s); } }