问题
Up until now I’ve managed to do various, simple things such as assigning to variables, calculations and what not, compiled it and all that good stuff…
This section is about decisions using if
and else
statements. Here’s the code:
public class Decision
{
public static void main(String[] args)
{
if (argv[0].equals("xyz"))
System.out.println("Login successful");
else
System.out.println("Login incorrect");
}
}
So I compile the program in CMD and try to run it, but I get this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Decision.main(Decision.java:5)
I understand there's a problem probably somewhere in the code but can't seem to find it- and I know once I have it will be blatantly obvious!
回答1:
You probably didn't enter any command line arguments, so the args
array is of length 0, hence the ArrayIndexOutOfBoundsException
.
Check the length first, and short-circuit your condition if the length isn't at least 1:
if (args.length >= 1 && args[0].equals("xyz"))
args[0]
won't be evaluated, and won't throw an ArrayIndexOutOfBoundsException
, if args.length >= 1
is false
, which makes the whole condition false
.
回答2:
if (argv.length > 0 && argv[0].equals("xyz")) {
…
} else {
…
}
回答3:
Why dont you just add a check to see if your array is empty? Something like:
if(argv.length == 0)
{
argv[0] = "";
}
//everything else...
来源:https://stackoverflow.com/questions/19526899/array-index-out-of-bounds-when-getting-arguments