package day12_01;/* * 導包;建立對象;調用方法 * 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); }}
成員方法
package day12_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("您輸入的資料有誤"); } }}
常用的兩個方法
package day12_03;import java.util.Scanner;/* * 常用的兩個方法 * public int nextInt() * public String nextLine() * * 出現問題:先擷取一個數值,再擷取一個字串 * 主要原因:分行符號號\n * 解決問題: * 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); int a=sc.nextInt(); Scanner sc2=new Scanner(System.in); String s=sc2.nextLine(); System.out.println("a:"+a+",s:"+s); }}