分析理解:Scanner sc = new Scanner(System.in);
package cn.itcast_01; /* * Scanner:用於接收鍵盤錄入數據。 * * 前面的時候: * A:導包 * B:創建對象 * C:調用方法 * * 分析理解:Scanner sc = new Scanner(System.in); * System類下有一個靜態的字段: * public static final InputStream in; 標准的輸入流,對應着鍵盤錄入。 * * InputStream is = System.in; * * class Demo { * public static final int x = 10; * public static final Student s = new Student(); * } * int y = Demo.x; * Student s = Demo.s; * * * 構造方法: * Scanner(InputStream source) */ import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.println("x:" + x); } }
Scanner類的hasNextInt()和nextInt()方法
package cn.itcast_02; import java.util.Scanner; /* * 基本格式: * public boolean hasNextXxx():判斷是否是某種類型的元素 * public Xxx nextXxx():獲取該元素 * * 舉例:用int類型的方法舉例 * public boolean hasNextInt() * public int nextInt() * * 注意: * InputMismatchException:輸入的和你想要的不匹配 */ 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("你輸入的數據有誤"); } } }
Scanner類中的nextLine()產生的換行符問題
package cn.itcast_03; import java.util.Scanner; /* * 常用的兩個方法: * public int nextInt():獲取一個int類型的值 * public String nextLine():獲取一個String類型的值 * * 出現問題了: * 先獲取一個數值,在獲取一個字符串,會出現問題。 * 主要原因:就是那個換行符號的問題。 * 如何解決呢? * A:先獲取一個數值后,在創建一個新的鍵盤錄入對象獲取字符串。 * B:把所有的數據都先按照字符串獲取,然后要什么,你就對應的轉換為什么。 */ public class ScannerDemo { public static void main(String[] args) { // 創建對象 Scanner sc = new Scanner(System.in); // 獲取兩個int類型的值 // int a = sc.nextInt(); // int b = sc.nextInt(); // System.out.println("a:" + a + ",b:" + b); // System.out.println("-------------------"); // 獲取兩個String類型的值 // String s1 = sc.nextLine(); // String s2 = sc.nextLine(); // System.out.println("s1:" + s1 + ",s2:" + s2); // System.out.println("-------------------"); // 先獲取一個字符串,在獲取一個int值 // String s1 = sc.nextLine(); // int b = sc.nextInt(); // System.out.println("s1:" + s1 + ",b:" + b); // System.out.println("-------------------"); // 先獲取一個int值,在獲取一個字符串,這里會出問題 // int a = sc.nextInt(); // String s2 = sc.nextLine(); // System.out.println("a:" + a + ",s2:" + s2); // System.out.println("-------------------"); int a = sc.nextInt(); Scanner sc2 = new Scanner(System.in); String s = sc2.nextLine(); System.out.println("a:" + a + ",s:" + s); } }