1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class CommandLineOptions {
  4. private static Map<String, String> options = new HashMap<>();
  5. public static void processOptions(String[] args) {
  6. // Process command-line arguments
  7. for (int i = 0; i < args.length; i++) {
  8. String arg = args[i];
  9. if (arg.startsWith("--")) {
  10. String optionName = arg.substring(2); // Remove "--" prefix
  11. String optionValue = null;
  12. if (i + 1 < args.length) {
  13. optionValue = args[i + 1];
  14. i++; // Skip the value argument
  15. }
  16. options.put(optionName, optionValue);
  17. } else {
  18. // Handle non-option arguments (e.g., program name, input file)
  19. // Can be customized based on your program's needs.
  20. // For backward compatibility, treat as positional arguments if needed.
  21. // For example, if the first argument is always the input file:
  22. // if (i == 0) {
  23. // inputFilePath = args[i];
  24. // }
  25. }
  26. }
  27. }
  28. public static String getOption(String optionName) {
  29. return options.getOrDefault(optionName, null); // Return null if option not found
  30. }
  31. public static void main(String[] args) {
  32. processOptions(args);
  33. // Example usage
  34. if (getOption("input") != null) {
  35. System.out.println("Input file: " + getOption("input"));
  36. }
  37. if (getOption("verbose") != null) {
  38. System.out.println("Verbose mode: " + getOption("verbose"));
  39. }
  40. if (getOption("output") != null) {
  41. System.out.println("Output file: " + getOption("output"));
  42. }
  43. if (getOption("nonExistentOption") == null){
  44. System.out.println("nonExistentOption not found");
  45. }
  46. }
  47. }

Add your comment