From 69b8cc535a1876cb30cfda55e16962f0d7abc835 Mon Sep 17 00:00:00 2001 From: Svjatoslav Agejenko Date: Thu, 20 Mar 2025 23:52:20 +0200 Subject: [PATCH] Ability to ask for integer --- .../commons/cli_helper/CLIHelper.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/src/main/java/eu/svjatoslav/commons/cli_helper/CLIHelper.java b/src/main/java/eu/svjatoslav/commons/cli_helper/CLIHelper.java index fe00e70..e86c58b 100755 --- a/src/main/java/eu/svjatoslav/commons/cli_helper/CLIHelper.java +++ b/src/main/java/eu/svjatoslav/commons/cli_helper/CLIHelper.java @@ -172,6 +172,64 @@ public class CLIHelper { } } + /** + * 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. + * + * + * @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, -- 2.20.1