import java.util.Arrays;
public class ConfigValidator {
public static void validateConfig(String[] args) {
// Validate the number of arguments
if (args == null || args.length < 2) {
System.err.println("Error: Incorrect number of arguments. Usage: <program> <input_file> <option1> <value1>");
System.exit(1); // Exit with an error code
}
String inputFile = args[1]; // Get the input file name
String option1 = args[2]; // Get the first option
String value1 = args[3]; // Get the value for the first option
// Validate the input file exists
if (!new java.io.File(inputFile).exists()) {
System.err.println("Error: Input file '" + inputFile + "' does not exist.");
System.exit(1);
}
// Validate option 1
if (!option1.equals("flag1") && !option1.equals("flag2")) {
System.err.println("Error: Invalid option. Must be 'flag1' or 'flag2'.");
System.exit(1);
}
// Validate value 1 - example: check if it's a number
try {
Double.parseDouble(value1); // Attempt to parse as a double
} catch (NumberFormatException e) {
System.err.println("Error: Value for option '" + option1 + "' must be a number.");
System.exit(1);
}
// Example of validating a range
if (option1.equals("flag2")) {
int value2 = Integer.parseInt(value1); // Get the value
if (value2 < 0 || value2 > 100) {
System.err.println("Error: Value for option 'flag2' must be between 0 and 100.");
System.exit(1);
}
}
// If all validations pass, the configuration is valid
System.out.println("Configuration is valid.");
}
public static void main(String[] args) {
//Example usage for testing
String[] validArgs = {"myprogram", "input.txt", "flag1", "123"};
String[] invalidArgs1 = {"myprogram", "input.txt", "invalid_flag", "abc"};
String[] invalidArgs2 = {"myprogram", "nonexistent.txt", "flag1", "123"};
validateConfig(validArgs);
//validateConfig(invalidArgs1);
//validateConfig(invalidArgs2);
}
}
Add your comment