Home > Software design >  Check if command line arguments are in a correct form
Check if command line arguments are in a correct form

Time:01-16

So if for instance my programm is correctly started like this:

java Test Tim;John;10;20

However I want to prevent users from entering something else than this form.

So whenever the command line arguments are not in the form String;String;int;int I want my programm to exit and print an error code.

I have no idea how to do this. For the case that if someone enters nothing I just used try catch with ArrayIndexOutofBounds but I dont know on how to particularly catch every possible command line arguments which is not in the correct form.

CodePudding user response:

I hope it give you some idea:

 public static void main(String[] args) {
        args = args[0].split(";");
        if (args.length != 4) {
            throw new IllegalArgumentException("Program starts with parameters like this: (String, String, int, int)");
        }

        try {
            int firstInt = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Program starts with parameters like this: (OK, OK, int, int)");
        }

        try {
            int secondInt = Integer.parseInt(args[3]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Program starts with parameters like this: (OK, OK, OK, int)");
        }
    }
  •  Tags:  
  • Related