java - 打印 args[] 数组的大小 - 越界异常错误

标签 java indexoutofboundsexception args

我理解为什么会抛出越界错误,但不明白为什么会在这种情况下发生。

在类(class)教科书中,一些练习包括编写代码“打印出其命令行参数”和“添加其两个命令行参数”

我编写的两个代码是:

public class AddToCommandLine {
    public static void main(String[] args) 
    {
    int x = Integer.parseInt(args[0]);
    int y = Integer.parseInt(args[1]);
    System.out.println(x+y);
    }

还有

public class AddToCommandLine {
    public static void main(String[] args) 
    {
    int x = Integer.parseInt(args[0]);
    System.out.println(x+1);
    }
}

对于两者,我得到相同的“线程“main”中的异常”j ava.lang.ArrayIndexOutOfBoundsException:0 在 AddToCommandLine.main(AddToCommandLine.java:4)"

我不明白为什么。

提前谢谢

最佳答案

如果你只是运行程序而不传递任何参数,那么 args[] 的大小将为 0。这里你试图访问 [0] 即第一个元素和 [1] 即第二个元素。因此异常(exception)。

我建议你写这样的东西,

public class AddToCommandLine {
    public static void main(String[] args) 
    { 
        if(args != null && args.length == 2)
        {
            int x = Integer.parseInt(args[0]);
            int y = Integer.parseInt(args[1]);
            System.out.println(x+y);
        }
        else
            System.out.println("Wrong number of command line arguments. This program require 2 arguments");
    }
}

您需要使用 java 命令传递参数

java AddToCommandLine 1 2

如果你想从某个 IDE 运行,那么你必须去运行配置并在那里添加参数。

关于java - 打印 args[] 数组的大小 - 越界异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29959327/

相关文章:

java - Guava Multimap 到 HashMap

java - Tapestry 5.2 : Update Zone with data from Form

function - Clojure:如何将剩余参数 "& args"发送到列表中?

python-3.x - 如何将命令行 "key=value"args 转换为字典?

java - Vertx 抛出 "Response has already been written"IllegalStateException

java - 签名 PADES 顺序或并行

java - 在数组中的特定索引处插入项目 - IndexOutOfBounds 异常

java - 修复 ArrayList 中的 IndexOutOfBounds 异常

java - MedianCalc() 方法给我 IndexOutOfBounds 异常

java - 使用多个 int 数组作为参数