1 package cn.itcast_01; 2 /*
3 Scanner: 用於接收鍵盤錄入數據. 4 錄入數據格式: 5 導包,建立對象,調用方法 6
7 System類下有一個靜態字段: 8 public static final InputStream in; 標準輸入流, 對應鍵盤輸入 9 InputStream is = System.in; 10
11 class Demo 12 { 13 public static final int x = 10; 14 public static final Student s = new Student(); 15
16 } 17 int y = Demo.x; 18 Student s = Demo.s; 19
20 構造方法: 21 Scanner(InputStream source) 22
23 */
24
25 import java.util.Scanner; 26 public class ScannerDemo 27 { 28 public static void main(String[] args){ 29 //建立對象
30 Scanner s = new Scanner(System.in); 31 int x = s.nextInt(); 32 System.out.println("x = " + x); 33 } 34 }
/* 基本格式: public boolean hasNextXxx(): 判斷是否爲某事類型的元素 public Xxx nextXxx(): 獲取該元素 舉例: int 類型 public boolean hasNextInt() public int nextInt() 注意: InputMismatchException: 輸入不匹配異常 */
package cn.itcast_02; import java.util.Scanner; public class ScannerDemo2 { public static void main(String[] args){ //建立對象
Scanner sc = new Scanner(System.in); //輸入字符串致使InputMisMatchException; // int x = sc.nextInt(); // System.out.println("x = " + x);
if(sc.hasNextInt()){ int x = sc.nextInt(); System.out.println("x = " + x); }else{ System.out.println("你輸入錯誤"); } } }