<一> 、使用標準輸入串System.in
system.in.read()方法的作用是從鍵盤讀出一個字符,然後返回它的Unicode碼。按下Enter結束輸入
char c = 0; //必須初始化
try {
c = (char) System.in.read(); //錄入的是Unicode碼
} catch(IOException e){
e.printStackTrace();
}
System.out.println(c);
用System.in.read()時,我們在鍵盤上按下的任何一個鍵都會被當做是輸入值,包括Enter鍵也會被當做是一個值!當我們按下Enter的時候,實際上發送兩個鍵值:一個回車\t(13),一個是換行\n(10)
<二>、使用Scanner取得一個字符串或一組數字
通過new Scanner(System.in)創建一個Scanner,控制檯會一直等待輸入,直到敲回車鍵結束,把所輸入的內容傳給Scanner,
作爲掃描對象。如果要獲取輸入的內容,則只需要調用Scanner的nextLine()方法即可。
在新增一個Scanner對象時需要一個System.in對象,因爲實際上還是System.in在取得用戶輸入。Scanner的next()方法用
以取得用戶輸入的字符串;nextInt()將取得的輸入字符串轉換爲整數類型;同樣,nextFloat()轉換成浮點型;nextBoolean()
轉換成布爾型。
Scanner scan = new Scanner(System.in);
String read = scan.nextLine();
System.out.println("輸入數據:"+read);
<三>、使用BufferedReader取得含空格的輸入
*Scanner取得的輸入以space, tab, enter 鍵爲結束符,
*要想取得包含space在內的輸入,可以用java.io.BufferedReader類來實現
*使用BufferedReader的readLine( )方法
*必須要處理java.io.IOException異常
BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
//java.io.InputStreamReader繼承了Reader類
String read = null;
System.out.print("輸入數據:");
try {
read = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("輸入數據:"+read);