System.in
The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
public final static InputStream in = null;
Scanner scan = new Scanner(System.in) ; // 從鍵盤接收數據
System.in代表InputStream輸入流,也相當於是一座橋梁,起到連接鍵盤輸入與scan對象的作用。scan對象僅僅只是一個對象,它在構造的同時指向了這個輸入流,並擁有一些可以操作的方法,比如:
String str = scan.next() ; // 接收數據
next方法會從輸入流中獲取一條(一行)數據,取決於是否按下回車。每次回車,意味着已經輸入了一行數據,緊接着這行數據會被scan對象獲取和使用。如果想持續的獲取數據,那么可以這樣實現:
String str = scan.next(); // 接收數據
do{
System.out.println("輸入的數據為:" + str) ;
} while((str= scan.next())!=null);//不能直接把字符串轉換為布爾值
完整代碼:
import java.util.* ; public class ScannerDemo01{ public static void main(String args[]){ Scanner scan = new Scanner(System.in) ; // 從鍵盤接收數據 System.out.print("輸入數據:") ; String str = scan.next(); // 接收數據 do{ System.out.println("輸入的數據為:" + str) ; } while((str= scan.next())!=null); } };