import java.util.HashMap;
import java.util.Map;
public class CommandLineOptions {
private static Map<String, String> options = new HashMap<>();
public static void processOptions(String[] args) {
// Process command-line arguments
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--")) {
String optionName = arg.substring(2); // Remove "--" prefix
String optionValue = null;
if (i + 1 < args.length) {
optionValue = args[i + 1];
i++; // Skip the value argument
}
options.put(optionName, optionValue);
} else {
// Handle non-option arguments (e.g., program name, input file)
// Can be customized based on your program's needs.
// For backward compatibility, treat as positional arguments if needed.
// For example, if the first argument is always the input file:
// if (i == 0) {
// inputFilePath = args[i];
// }
}
}
}
public static String getOption(String optionName) {
return options.getOrDefault(optionName, null); // Return null if option not found
}
public static void main(String[] args) {
processOptions(args);
// Example usage
if (getOption("input") != null) {
System.out.println("Input file: " + getOption("input"));
}
if (getOption("verbose") != null) {
System.out.println("Verbose mode: " + getOption("verbose"));
}
if (getOption("output") != null) {
System.out.println("Output file: " + getOption("output"));
}
if (getOption("nonExistentOption") == null){
System.out.println("nonExistentOption not found");
}
}
}
Add your comment