Javaでのユーザー入力の読み取りと書き込み
1. 前書き
このクイックチュートリアルでは、demonstrate several ways to use a console for user input and output in Javaを使用します。
入力を処理するためのScannerクラスのいくつかのメソッドを見てから、System.outを使用した簡単な出力をいくつか示します。
最後に、Java 6以降で使用可能なConsoleクラスを、コンソールの入力と出力の両方に使用する方法を説明します。
2. System.inからの読み取り
最初の例では、use the Scanner class in the java.util package to obtain the input from System.in —「標準」入力ストリームを使用します。
Scanner scanner = new Scanner(System.in);
use the nextLine() method to read an entire line of input as a Stringを実行して、次の行に進みましょう。
String nameSurname = scanner.nextLine();
ストリームからuse the next() method to get the next input tokenすることもできます。
String gender = scanner.next();
数値入力を期待している場合は、use nextInt() to get the next input as an intプリミティブを使用でき、同様に、use nextDouble() to get a variable of type doubleを使用できます。
int age = scanner.nextInt();
double height = scanner.nextDouble();
Scanner classは、hasNext_Prefix() methods which return true if the next token can be interpreted as a corresponding data typeも提供します。
たとえば、hasNextInt() methodを使用して、次のトークンを整数として解釈できるかどうかを確認できます。
while (scanner.hasNextInt()) {
int nmbr = scanner.nextInt();
//...
}
また、 hasNext(Pattern pattern) メソッドをcheck if the following input token matches a patternに使用できます。
if (scanner.hasNext(Pattern.compile("www.example.com"))) {
//...
}
Scannerクラスの使用に加えて、we can also use an InputStreamReader with System.in to get the input from the console:
BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
そして、入力を読み取って整数に解析できます。
int i = Integer.parseInt(buffReader.readLine());
3. System.outへの書き込み
コンソール出力には、OutputStreamのタイプであるSystem.out — an instance of the PrintStream class, を使用できます。
この例では、コンソール出力を使用して、ユーザー入力のプロンプトを提供し、ユーザーに最終的なメッセージを表示します。
use the println() method to print a String and terminate the line:
System.out.println("Please enter your name and surname: ");
または、use the print() method, which works similarly to println(), but without terminating the line:
System.out.print("Have a good");
System.out.print(" one!");
4. 入力と出力にConsoleクラスを使用する
JDK 6以降では、java.io packageのConsole classを使用して、コンソールからの読み取りとコンソールへの書き込みを行うことができます。
Consoleオブジェクトを取得するために、System.console()を呼び出します。
Console console = System.console();
次に、Console classのreadLine() メソッドをwrite a line to the console and then read a line from the consoleに使用しましょう。
String progLanguauge = console.readLine("Enter your favourite programming language: ");
パスワードなどの機密情報を読み取る必要がある場合は、readPassword()メソッドを使用してprompt a user for a password and read the password from the console with echoing disabledを実行できます。
char[] pass = console.readPassword("To finish, enter password: ");
String引数を使用してuse the Console class to write output to the console, for example, using the printf() methodを実行することもできます。
console.printf(progLanguauge + " is very interesting!");
5. 結論
この記事では、いくつかのJavaクラスを使用してコンソールユーザーの入出力を実行する方法を示しました。
いつものように、このチュートリアルのコードサンプルはover on GitHubで提供されます。