Consoleクラスを使用してユーザーから入力を取得しようとしていますが、を呼び出すとnullオブジェクトが返されますSystem.console()
。System.consoleを使用する前に何かを変更する必要がありますか?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Consoleクラスを使用してユーザーから入力を取得しようとしていますが、を呼び出すとnullオブジェクトが返されますSystem.console()
。System.consoleを使用する前に何かを変更する必要がありますか?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
回答:
コンソールを使用して入力を読み取る(IDEの外部でのみ使用可能):
System.out.print("Enter something:");
String input = System.console().readLine();
別の方法(どこでも機能):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console()はIDEでnullを返します。
したがって、本当に使用する必要がある場合はSystem.console()
、McDowellからこのソリューションをお読みください。
readLine()
がに存在しないメソッドを提供していることですInputStreamReader
。
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
nextLine()
は非常に厄介です。コンソールから行全体を取得しようとすると、せいぜい頭痛の種になるでしょう。
in.nextLine()
問題が発生する例を挙げていただけませんか?
java.util.NoSuchElementException
よくわかりません。
コンソール/キーボードから入力文字列を読み取る方法はいくつかあります。次のサンプルコードは、Javaを使用してコンソール/キーボードから文字列を読み取る方法を示しています。
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
コード使用java.io.Console
クラスの最後の部分。System.console()
Eclipseを介してデモコードを実行しているときは、コンソールインスタンスを取得できません。Eclipseはアプリケーションをシステムコンソールのトップレベルプロセスとしてではなく、バックグラウンドプロセスとして実行するためです。
環境によって異なります。javaw
たとえば、Swing UIを実行している場合は、、表示するコンソール。IDE内で実行している場合は、特定のIDEのコンソールIOの処理に大きく依存します。
ただし、コマンドラインからは問題ありません。サンプル:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
これだけで実行しますjava
:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
もう1つのオプションは、を使用System.in
することです。これは、BufferedReader
行を読み取るためにラップするか、またはScanner
(再度ラップするSystem.in
)使用することができます。
コンソールからの読み取りに関して、ここでいくつかの良い答えが見つかりました。別の方法として、コンソールから読み取るために「スキャナー」を使用します。
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
close()
この場合、スキャナーを呼び出したくない場合があります。スキャナーがSystem.inを閉じ、アプリケーションが後で読み取れないようにするためです。(後で読むとエラー「行が見つかりません」がスローされます)
これを試して。これがお役に立てば幸いです。
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
以下は、athspkの回答を受け取り、ユーザーが「exit」と入力するまで継続的にループする回答にします。また、このコードを取得してテスト可能にしたフォローアップ回答も作成しました。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
出力例:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
Text-IOを書いた IDE内からアプリケーションを実行するときSystem.console(の問題に対処することができますライブラリは、)ヌルいます。
McDowellによって提案されたものと同様の抽象化レイヤーを導入しますます。System.console()がnullを返すと、ライブラリはSwingベースのコンソールに切り替わります。
さらに、Text-IOには一連の便利な機能があります。
使用例:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
では、このイメージあなたはSwingベースのコンソールで実行されている上記のコードを見ることができます。