Array index out of bounds when getting arguments

梦想与她 提交于 2019-11-27 04:53:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!