作為 Codegym 大學課程一部分的導師授課片段。報名參加完整課程。


“朋友,你的時間到了,我現在要給你講講鍵盤輸入法。”

“我們使用System.out在屏幕上顯示數據。要接收輸入,我們將使用System.in。”

“聽起來很簡單。”

“但System.in有一個缺點——它只允許我們從鍵盤讀取字符代碼。為了解決這個問題並一次讀取大塊數據,我們將使用更複雜的結構:”

例1
從鍵盤輸入字符串和數字
InputStream inputStream = System.in;
Reader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String name = bufferedReader.readLine(); //Read a string from the keyboard
String sAge = bufferedReader.readLine(); //Read a string from the keyboard
int nAge = Integer.parseInt(sAge); //Convert the string to a number.
示例 2
上一個示例的更緊湊版本:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String name = reader.readLine();
String sAge = reader.readLine();
int nAge = Integer.parseInt(sAge);
示例 3
更緊湊
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = scanner.nextInt();

“任何問題?”

“呃……我什麼都沒聽懂。”

“要從鍵盤讀取字符串,最方便的方法是使用 BufferedReader 對象。但要做到這一點,您必須傳入要從中讀取數據的對象。在本例中,是System.in。”

“但是System.inBufferedReader不兼容,所以我們使用另一個適配器——另一個InputStreamReader對象。”

“我想我現在明白了。這個Scanner 類是什麼?”

“Scanner 可能很方便,但不是很有用。問題是,隨著你的繼續(學習和工作),你會經常使用 BufferedReader 和 InputStreamReader,但很少使用 Scanner。它在我們的例子中很方便,但在未來它不會經常有用。所以我們不會經常使用它。”

“這似乎很清楚,但我不確定我是否理解了一切。”