簡體   English   中英

使用Java從用戶那里獲取輸入

[英]Take input from the user using java

我正在使用此方法創建控制台

MessageConsole console = new MessageConsole("", null);
console.activate();
ConsolePlugin.getDefault().getConsoleManager()
        .addConsoles(new IConsole[] { console });
MessageConsoleStream stream = console.newMessageStream();
System.setOut(new PrintStream(stream, true));

我嘗試了用於輸入的普通方法,但無法正常工作這是我嘗試過的代碼

[1]這會打印“輸入字符串”,但不允許您在控制台中編寫

Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String s = in.nextLine();
System.out.println("You entered string " + s);

[2],此打印為null

BufferedReader columnInput = new BufferedReader(new InputStreamReader(
        System.in));
try {
    System.out.println(columnInput.readLine());
    // System.out.println("#read mflkerf: " );
} catch (IOException e) {

}

您的第一個代碼段:

Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
String s = in.nextLine();
System.out.println("You entered string " + s);

確實有效。 我猜是因為您使用System.setOut重新分配了標准輸出流,所以您不再看到從System.out.println打印的輸出

嘗試創建一個將新控制台輸出流打印到文件或某個位置的線程,您將看到輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM