Add FloatOption class for CLI parameter parsing
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Sun, 21 Apr 2024 15:51:11 +0000 (18:51 +0300)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Sun, 21 Apr 2024 15:51:25 +0000 (18:51 +0300)
This commit introduces a new FloatOption class to handle float type parameters in the command-line interface. This new class ensures that the input argument is correctly parsed as a float and includes appropriate error handling for invalid inputs.

src/main/java/eu/svjatoslav/commons/cli_helper/parameter_parser/parameter/FloatOption.java [new file with mode: 0644]

diff --git a/src/main/java/eu/svjatoslav/commons/cli_helper/parameter_parser/parameter/FloatOption.java b/src/main/java/eu/svjatoslav/commons/cli_helper/parameter_parser/parameter/FloatOption.java
new file mode 100644 (file)
index 0000000..f84b334
--- /dev/null
@@ -0,0 +1,35 @@
+package eu.svjatoslav.commons.cli_helper.parameter_parser.parameter;
+
+import eu.svjatoslav.commons.cli_helper.parameter_parser.Option;
+import eu.svjatoslav.commons.cli_helper.parameter_parser.ParameterCount;
+
+public class FloatOption extends Option<Float, FloatOption> {
+
+        public FloatOption(final String description) {
+            super(description, ParameterCount.ONE);
+        }
+
+        @Override
+        public java.lang.String describeFormat() {
+            return "Float.";
+        }
+
+        @Override
+        public Float getValue() {
+            if (parameters.size() != 1)
+                throw new RuntimeException("Parameter " + description
+                        + " shall have exactly 1 argument.");
+            return Float.parseFloat(parameters.get(0));
+        }
+
+        @Override
+        public boolean isValid(final java.lang.String value) {
+            try {
+                java.lang.Float.valueOf(value);
+                return true;
+            } catch (final NumberFormatException e) {
+                return false;
+            }
+        }
+}
+