Question

I am wondering if the java line if (args[0].length > 2) is a valid line. I'm taking in command-line arguments, and I want to find out if the amount of numbers in the first array is longer than two digits. For example, the year 2014 would allow the if statement to be true. If the user's input was for example 52 then the if statement wouldn't be true and it'd move onto an else if statement below.

No correct solution

OTHER TIPS

It's a valid line if args is declared as a String[][] - but that wouldn't be how a main method would be declared. length is a valid member of an array, but it's not a (public) member of the String class.

If you're trying to check the length of a string, you want the length() method instead. For example:

if (args[0].length() > 2)

You might want to first check that there are some arguments, using args.length. For example:

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("You need to give me an argument!");
        return;
    }
    if (args[0].length() > 2) {
        System.out.println("The first argument has more than 2 characters");
    } else {
        System.out.println("The first argument has 0-2 characters");
    }
}

Yes you can with String#length() method and also I think null check should be added

if (args[0]!=null && args[0].length() > 2)

If args[0] is an array and is not null then

if (args[0].length > 2)

is a valid option.

 if (args[0].length > 2)

Its invalid expression bcoz String don't contain any length field.

Change to

if (args[0].length() > 2) to get the length of the String

You are talking about command line arguments, so...

I was wondering if the java line "if (args[0].length > 2)" is a valid line.

No. args is a String[], therefore args[0] is a String. And a String does not have a length public static field.

However:

I want to find out if the amount of numbers in the first array is longer than two digits

So, as mentioned, args[0] is a String. It is not an array!. Unlike C, for instance, there is no "direct mapping" of a String to a char[]. In fact, C has nothing like String. With Java, you'd have to use .toCharArray() to get a char[] from a String.

If you want to find if a String has more than two numbers, then you should write:

if (args[0].matches("[0-9]{2,}"))

This will check both that the string is 2 characters long or more, and that all characters in it are digits.

This uses a regular expression to check your argument. If the regex succeeds, you can then convert to an integer using:

Integer.parseInt(args[0])

provided there is no overflow!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top