Improve user interaction.
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Wed, 19 Mar 2025 22:32:46 +0000 (00:32 +0200)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Wed, 19 Mar 2025 22:32:46 +0000 (00:32 +0200)
Better way to ask boolean.

src/main/java/eu/svjatoslav/commons/cli_helper/CLIHelper.java

index 08354b7..fb98f12 100755 (executable)
@@ -24,31 +24,24 @@ public class CLIHelper {
      * @param prompt to show to the user
      * @return <code>true</code> is user answered affirmative.
      */
-    public static boolean askBoolean(final String prompt) {
+    public static boolean askBoolean(final String prompt, final boolean defaultValue) {
 
-        final BufferedReader br = new BufferedReader(new InputStreamReader(
-                System.in));
+            while (true)
+            {
+                String line = askString(prompt + " [" + (defaultValue ? "Y/n" : "y/N") + "]: ");
+                if (line == null) return defaultValue;
 
-        while (true)
-            try {
-                System.out.print(prompt);
-
-                String line = br.readLine();
-                if (line != null) {
-                    final String userInput = line.toLowerCase();
+                final String userInput = line.toLowerCase();
 
-                    if ("y".equals(userInput) || "yes".equals(userInput)
-                            || "true".equals(userInput))
-                        return true;
+                if ("y".equals(userInput) || "yes".equals(userInput)
+                        || "true".equals(userInput))
+                    return true;
 
-                    if ("n".equals(userInput) || "no".equals(userInput)
-                            || "false".equals(userInput))
-                        return false;
-                }
+                if ("n".equals(userInput) || "no".equals(userInput)
+                        || "false".equals(userInput))
+                    return false;
                 System.out
                         .println("Invalid input. You shall enter y/yes/true or n/no/false.");
-            } catch (final IOException ioe) {
-                ioe.printStackTrace();
             }
     }