Commits

Alexander Nordlund  committed 35326ef

queryUser(), ask the user question and do some validation.

  • Participants
  • Parent commits de4662d

Comments (0)

Files changed (1)

File InputHandler.java

+package local.alex.conveniences;
+
+import java.util.Scanner;
+import org.omg.CORBA.DynAnyPackage.InvalidValue;
+
+public class InputHandler {
+	public static String queryUser(Scanner scanner, String question,
+			String defaultValue, String... extras) {
+		// TODO: typechecking? if(input instanceof arg)
+
+		while (true) {
+			try {
+				StringBuilder queryString = new StringBuilder();
+				queryString.append(question + " " + "[" + defaultValue);
+				for (String s : extras) {
+					queryString.append("/" + s);
+				}
+				queryString.append("]: ");
+
+				System.out.print(queryString);
+
+				String input = scanner.nextLine();
+
+				if (input.replaceAll("\\s", "").equals("")) {
+					return defaultValue;
+				} else {
+					// Is it the defaultValue?
+					if (input.toLowerCase().equals(defaultValue.toLowerCase())) {
+						return defaultValue;
+					}
+					// Is it the same as one of the choices?
+					else if (extras.length > 0) {
+						for (String s : extras) {
+							if (input.toLowerCase().equals(s.toLowerCase())) {
+								return s;
+							}
+						}
+						// TODO: replace extras.toString()
+						throw new InvalidValue(input
+								+ " is invalid, must be one of:"
+								+ extras.toString());
+					} else {
+						return input;
+					}
+				}
+			} catch (InvalidValue e) {
+				System.out
+						.println("Invalid input, please enter one of the choices.");
+			}
+		}
+
+	}
+}
+