1. import java.util.Arrays;
  2. public class ConfigValidator {
  3. public static void validateConfig(String[] args) {
  4. // Validate the number of arguments
  5. if (args == null || args.length < 2) {
  6. System.err.println("Error: Incorrect number of arguments. Usage: <program> <input_file> <option1> <value1>");
  7. System.exit(1); // Exit with an error code
  8. }
  9. String inputFile = args[1]; // Get the input file name
  10. String option1 = args[2]; // Get the first option
  11. String value1 = args[3]; // Get the value for the first option
  12. // Validate the input file exists
  13. if (!new java.io.File(inputFile).exists()) {
  14. System.err.println("Error: Input file '" + inputFile + "' does not exist.");
  15. System.exit(1);
  16. }
  17. // Validate option 1
  18. if (!option1.equals("flag1") && !option1.equals("flag2")) {
  19. System.err.println("Error: Invalid option. Must be 'flag1' or 'flag2'.");
  20. System.exit(1);
  21. }
  22. // Validate value 1 - example: check if it's a number
  23. try {
  24. Double.parseDouble(value1); // Attempt to parse as a double
  25. } catch (NumberFormatException e) {
  26. System.err.println("Error: Value for option '" + option1 + "' must be a number.");
  27. System.exit(1);
  28. }
  29. // Example of validating a range
  30. if (option1.equals("flag2")) {
  31. int value2 = Integer.parseInt(value1); // Get the value
  32. if (value2 < 0 || value2 > 100) {
  33. System.err.println("Error: Value for option 'flag2' must be between 0 and 100.");
  34. System.exit(1);
  35. }
  36. }
  37. // If all validations pass, the configuration is valid
  38. System.out.println("Configuration is valid.");
  39. }
  40. public static void main(String[] args) {
  41. //Example usage for testing
  42. String[] validArgs = {"myprogram", "input.txt", "flag1", "123"};
  43. String[] invalidArgs1 = {"myprogram", "input.txt", "invalid_flag", "abc"};
  44. String[] invalidArgs2 = {"myprogram", "nonexistent.txt", "flag1", "123"};
  45. validateConfig(validArgs);
  46. //validateConfig(invalidArgs1);
  47. //validateConfig(invalidArgs2);
  48. }
  49. }

Add your comment