}
}
+ /**
+ * Asks the user for an integer value using the specified prompt on the command line.
+ * The user is prompted until a valid integer (within optional ranges) is provided.
+ * <ul>
+ * <li>If {@code defaultValue} is specified and user presses Enter, that default is returned.</li>
+ * <li>If {@code defaultValue} is {@code null} and user presses Enter, returns {@code null}.</li>
+ * <li>If {@code min} is not {@code null}, we enforce that the entered integer is {@code >= min}.</li>
+ * <li>If {@code max} is not {@code null}, we enforce that the entered integer is {@code <= max}.</li>
+ * </ul>
+ *
+ * @param prompt The prompt displayed to the user
+ * @param defaultValue The default long if user simply presses Enter (may be null)
+ * @param min The minimum acceptable value (inclusive), or null if no lower bound
+ * @param max The maximum acceptable value (inclusive), or null if no upper bound
+ * @return An integer value that the user entered, or the defaultValue, or null if no defaultValue was given
+ */
+ public Integer askInteger(String prompt, Integer defaultValue, Integer min, Integer max) {
+ while (true) {
+ // If we have a defaultValue, display it in brackets; otherwise display no default
+ String displayPrompt = prompt
+ + (defaultValue != null ? " [" + defaultValue + "]" : "")
+ + ": ";
+
+ // Read user input
+ System.out.print(displayPrompt);
+ String input = new Scanner(System.in).nextLine().trim();
+
+ // If user just pressed Enter:
+ if (input.isEmpty()) {
+ // If a defaultValue was supplied, return it; else return null
+ return defaultValue;
+ }
+
+ // Parse long value
+ try {
+ int parsedValue = Integer.parseInt(input);
+
+ // Check against min if specified
+ if (min != null && parsedValue < min) {
+ System.out.println("Value must be at least " + min + ".");
+ continue;
+ }
+
+ // Check against max if specified
+ if (max != null && parsedValue > max) {
+ System.out.println("Value must be at most " + max + ".");
+ continue;
+ }
+
+ // Parsed successfully within optional bounds
+ return parsedValue;
+
+ } catch (NumberFormatException e) {
+ System.out.println("Invalid number format. Try again.");
+ }
+ }
+ }
+
/**
* Asks the user for a string value using the specified prompt on the command line.
* If the user presses ENTER without typing anything and {@code defaultValue} is non-null,