normx222
normx222

Reputation: 25

Check if second argument exist in java

I'm passing two arguments to a java job and I want to print a message if either argument is empty. I tried a few things and still get an error when my second argument is empty. I can't get past having something for my first argument and nothing for my second.

if (args.length == 0)
if (args.length > 1)
if (args[0].equal(0) || args[1].equal(0))

Upvotes: 1

Views: 2043

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79620

As Basil Bourque has mentioned in the comment, the arguments to main method are String values i.e. if at all you need to check if the argument is 0, you need to check it as args[0].equals("0") instead of args[0].equal(0).

However, if I understood your question correctly, you only want to check if one or both of the arguments are missing. You can write your checks as follows:

if (args.length == 0) {
    System.out.println("Arguments are missing");
    // ...
} else if (args.length == 1) {
    System.out.println("The second arguments is missing");
    // ...
} else {
    // ...
}

Note that a bank or white space argument to main will automatically be discarded. Therefore, you do not need to test if any of the arguments are empty or blank.

Upvotes: 1

TomStroemer
TomStroemer

Reputation: 1560

Depends on your arguments.

You can use something like this:

if (args.length < 2 || args[0].isBlank() || args[1].isBlank()) {
   // do whatever you need to do :-)
   System.out.println("invalid arguments");
   return;
}

Notice that isBlank() needs Java 11, you can use isEmpty if you don't have Java 11, but that does not compare white spaces. Or you can use functions from Apache Commons StringUtils, etc. to check the length (or implement it yourself).

Upvotes: 1

Basil Bourque
Basil Bourque

Reputation: 340230

The arguments passed to the main method arrive as String objects. So you cannot compare to an integer number.

You can loop the arguments, checking to see if the string is empty or blank.

for( String arg : args )
{
    if( arg.isEmpty() || arg.isBlank() ) 
    {
        …
    } else 
    {
        int number = Integer.parseInt( arg ) ;  // Add try-catch for `NumberFormatException`.
        if( number == 0 ) { … }
    }
}

Upvotes: 0

Related Questions