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.
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");
}
}
See more on this question at Stackoverflow