获取参数时数组索引超出范围 [英] Array index out of bounds when getting arguments

查看:122
本文介绍了获取参数时数组索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经设法做了各种简单的事情,例如分配给变量,计算什么,没有,编译它以及所有好东西...

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…

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

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");  
    }
}

所以我在CMD中编译程序并尝试运行它,但我明白了:

So I compile the program in CMD and try to run it, but I get this:


在Decision.main(Decision.java)中,线程main中的异常java.lang.ArrayIndexOutOfBoundsException:0 :5)

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!

推荐答案

你可能没有输入任何命令行参数,所以 args 数组长度为0,因此 ArrayIndexOutOfBoundsException

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

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

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] 将不会被评估,并且不会抛出 ArrayIndexOutOfBoundsException ,如果 args.length> = 1 false ,这使整个条件 false

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

这篇关于获取参数时数组索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆