Tuesday, July 3, 2007

Read User Input

Here's a simple way to read user input from the standard input (stdin) console:


/**
* Display the given prompt and return the text types by the user (after his first Enter)

* @param prompt text to write in the stdout. Generaly used for asking the user to type something.
* @return userInput - text given by user in the console (stdout)
*/
public static String readUserInput(String prompt) {
System.out.println(prompt + " ( Type to confirm.) ");

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String userInput = "";
try {
userInput = bufferedReader.readLine();
if(log.isInfoEnabled()) {
log.info("Thanks ! ");
}
} catch (IOException ioe) {
log.error("Unable to read user input, Exception : " + ioe.getMessage());
}
return userInput;
}

No comments: