Java 获取参数时数组索引越界

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19526899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:01:57  来源:igfitidea点击:

Array index out of bounds when getting arguments

javaindexoutofboundsexception

提问by Curtis O'Neill

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 ifand elsestatements. Here's the code:

本节是关于使用ifelse语句的决策。这是代码:

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:

所以我在 CMD 中编译程序并尝试运行它,但我得到了这个:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Decision.main(Decision.java:5)

线程“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!

我知道代码中的某处可能存在问题,但似乎无法找到它 - 我知道一旦我找到它就会很明显!

回答by rgettman

You probably didn't enter any command line arguments, so the argsarray is of length 0, hence the ArrayIndexOutOfBoundsException.

您可能没有输入任何命令行参数,因此args数组的长度为 0,因此ArrayIndexOutOfBoundsException.

Check the length first, and short-circuit your condition if the length isn't at least 1:

首先检查长度,如果长度不至少为 1,则短路您的条件:

if (args.length >= 1 && args[0].equals("xyz"))

args[0]won't be evaluated, and won't throw an ArrayIndexOutOfBoundsException, if args.length >= 1is false, which makes the whole condition false.

args[0]不会被评估,也不会抛出ArrayIndexOutOfBoundsException, if args.length >= 1is false,这使得整个 condition false

回答by Alexander Kulyakhtin

if (argv.length > 0 && argv[0].equals("xyz")) {
   …
} else {
   …
}

回答by Shaun

Why dont you just add a check to see if your array is empty? Something like:

你为什么不添加一个检查来查看你的数组是否为空?就像是:

if(argv.length == 0)
{
    argv[0] = "";
}
//everything else...