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