System.in から読むことで、キー入力を実現可能。 ただし、キーを押すと即座に反応するタイプのプログラムをつくる場合には KeyListener など別の枠組みを利用。
文字コード utf-8 で eclipse を使っている場合には、 そのままではコンソールからキー入力すると文字化けした状態で入力される。 eclipse.exe と同じフォルダにある eclipse.ini に以下の1行を追加する。
-Dfile.encoding=UTF-8
Scanner もしくは InputStreamReader クラスを使う。
キーボードから1行入力されると、それをそのまま表示するプログラム (増田先生のサンプルの改造版)。 Enter のみの入力で終了する。
import java.io.*;
public class Echo {
private static BufferedReader userInputStreamReader;
static {
userInputStreamReader = new BufferedReader(new InputStreamReader(System.in));
}
/** System.in (通常キーボード) から1行読み込む */
private static String readLine() {
String inputString = ""; // エラー時には null ではなく "" になる
try {
inputString = userInputStreamReader.readLine();
}
catch (Exception e) {
e.printStackTrace();
}
return inputString;
}
/** サンプルの main */
public static void main(String[] args) {
String line;
while(true) {
line = readLine();
if(line.equals("")) // 空行なら終了
break;
System.out.println(line);
}
}
}
readLine()で一行読み込む。 static メソッドなので、インスタンスなしで使用可能。