Default value is optional when asking for boolean
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Wed, 26 Mar 2025 00:34:14 +0000 (02:34 +0200)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Wed, 26 Mar 2025 00:34:14 +0000 (02:34 +0200)
src/main/java/eu/svjatoslav/commons/cli_helper/CLIHelper.java

index 4804e6f..b77427c 100755 (executable)
@@ -28,18 +28,23 @@ public class CLIHelper {
      * If the user presses ENTER (empty input), the provided defaultValue is returned.
      *
      * @param prompt       the message to display to the user
-     * @param defaultValue the boolean value to return if the user provides no input
+     * @param defaultValue the boolean value to return if the user provides no input. If null, user must provide input.
      * @return {@code true} if the user answered affirmatively,
      *         {@code false} if they answered negatively,
      *         or {@code defaultValue} if input was empty
      */
-    public static boolean askBoolean(final String prompt, final boolean defaultValue) {
+    public static boolean askBoolean(final String prompt, final Boolean defaultValue) {
         while (true) {
             // Show the user something like "Continue? [Y/n]: " or "Continue? [y/N]: "
-            String line = askString(prompt + " [" + (defaultValue ? "Y/n" : "y/N") + "]: ");
+
+            String finalPrompt = prompt;
+            if (defaultValue != null){
+                finalPrompt = prompt + " [" + (defaultValue ? "Y/n" : "y/N") + "]: ";
+            }
+            String line = askString(finalPrompt);
 
             // If user provided an empty line, askString() returns null in this usage => default
-            if (line == null) {
+            if (line == null && defaultValue != null) {
                 return defaultValue;
             }