gpt4 book ai didi

java - 从 Java System.in 读取输入时出现问题

转载 作者:行者123 更新时间:2023-12-02 08:33:28 28 4
gpt4 key购买 nike

我正在尝试编写一种方法,提示用户在命令行上输入,并从标准输入中以字符串形式读取输入并返回。我第一次调用它时,一切正常。之后对 getInput() 的所有调用都不会返回任何内容。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* Prompts the user for input and reads from standard input (stdin).
* Note: Always check if the return is null!
*
* @param description Describes the user input.
* @return A String of the input, or null when failed.
*/
private String getInput(String description)
{
System.out.print(description + ": ");
String input = null;

InputStreamReader stream = null;
BufferedReader reader = null;
try {
// Open a stream to stdin
stream = new InputStreamReader(System.in);

// Create a buffered reader to stdin
reader = new BufferedReader(stream);

// Try to read the string
input = reader.readLine();

// Exhaust remainder of buffer
while (reader.skip(1) > 0) {
// Do nothing
}

} catch (IOException e) {
e.printStackTrace();
// Error reading input

} finally {
// Clean up readers and streams
try {
if (reader != null) {
reader.close();
}
if (stream != null) {
stream.close();
}
} catch (IOException e) {
}
}

System.out.print("\n");
return input;
}

/**
* Display the login prompt.
*/
private boolean promptLogin()
{
// prompt for user name and password
String user = getInput("Enter username");
String pass = getInput("Enter password");

if (user == null || pass == null) {
System.out.println("Invalid login information.");
return false;
}
// ..
}

最佳答案

您不得关闭标准输入流;这就是它只在第一次起作用的原因

/**
* Prompts the user for input and reads from standard input (stdin).
* Note: Always check if the return is null!
*
* @param description Describes the user input.
* @return A String of the input, or null when failed.
*/
private String getInput(String description) {
System.out.print(description + ": ");
String input = null;

InputStreamReader stream = null;
BufferedReader reader = null;
try {
// Open a stream to stdin
stream = new InputStreamReader(System.in);

// Create a buffered reader to stdin
reader = new BufferedReader(stream);

// Try to read the string
input = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}

return input;
}

/**
* Display the login prompt.
*/
private boolean promptLogin() {
// prompt for user name and password
String user = getInput("Enter username");
String pass = getInput("Enter password");

if (user == null || pass == null) {
System.out.println("Invalid login information.");
return false;
}

return true;
}

关于java - 从 Java System.in 读取输入时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5202060/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com