Added method variants with default values

Signed-off-by: Jim Martens <github@2martens.de>
This commit is contained in:
2017-04-19 13:13:24 +02:00
parent c9ec1aadc2
commit 8ecc87fa4b

View File

@ -7,20 +7,32 @@ import java.io.InputStreamReader;
/** /**
* Small helper class for forms. * Small helper class for forms.
*/ */
public class FormUtil { class FormUtil {
/** /**
* Reads a string from the console.
*
* @param label Label that is shown before the input
* @return read string
*/
static String readString(String label) {
return readString(label, "");
}
/**
* Reads a string from the console. * Reads a string from the console.
* *
* @param label Label that is shown before the input * @param label Label that is shown before the input
* @param defaultValue the default value in case an empty input is provided
* @return read string * @return read string
*/ */
static String readString(String label) { static String readString(String label, String defaultValue) {
String ret = null; String ret = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
try { try {
System.out.print(label+": "); System.out.print(label+": ");
ret = stdin.readLine(); ret = stdin.readLine();
ret = ret.isEmpty() ? defaultValue : ret;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -39,19 +51,31 @@ public class FormUtil {
password = String.valueOf(System.console().readPassword()); password = String.valueOf(System.console().readPassword());
return password; return password;
} }
/**
* Reads an integer from the console.
*
* @param label Label that is shown before the input
* @return read integer
*/
static int readInt(String label) {
return readInt(label, -1);
}
/** /**
* Reads an integer from the console. * Reads an integer from the console.
* *
* @param label Label that is shown before the input * @param label Label that is shown before the input
* @param defaultValue the default value
* @return read integer * @return read integer
*/ */
public static int readInt(String label) { static int readInt(String label, int defaultValue) {
int ret = 0; int ret = 0;
boolean finished = false; boolean finished = false;
String defaultValueStr = defaultValue == -1 ? "" : String.valueOf(defaultValue);
while(!finished) { while(!finished) {
String line = readString(label); String line = readString(label, defaultValueStr);
try { try {
ret = Integer.parseInt(line); ret = Integer.parseInt(line);