这种在Java中使用命令行参数的方式有什么问题?

huangapple go评论72阅读模式
英文:

What is wrong with this way of using command line arguments in Java?

问题

以下是翻译好的部分:

我的程序如下所示:

public class Main {
    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = a + b;
        System.out.print("和为" + a);
    }
}

我试图通过命令行参数传递两个整数,然后计算这两个数的和。我读到这是 Java 接收这些参数的方式,但是我得到了一个错误:

在主线程中的异常 java.lang.ArrayIndexOutofBoundsException

为什么会这样?为什么我的数组 args 越界了?

英文:

My program looks like this:

public class Main {
    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = a + b;
        System.out.print("Sum is" + a);
    }
}

I'm trying to give as command line arguments two integer numbers, then calculate the sum of the two. I read that this is the way for Java to receive these parameters, but I'm getting an error:

Exception in main thread java.lang.ArrayIndexOutofBoundsException

Why is that? Why am I out of bounds for my array args?

答案1

得分: 6

你的命令行需要像这样:

java Main 4 7

然后,在你的代码中,args 将包含两个元素,即 47

如果你的命令行是这样的:

java Main

那么 args 不包含任何元素,因此当你访问 args[0] 时会得到 ArrayIndexOutOfBoundsException,因为 args 不包含任何元素,所以无法访问第一个元素,因为它不存在。

请注意,通常最好先检查 args 包含多少个元素,因为正如你所见,很容易在没有所需数量的参数的情况下启动你的 Java 程序。

args.length

将返回 args 中的元素数量。

英文:

Your command line needs to be something like

java Main 4 7

Then, in your code, args would contain two elements, namely 4 and 7.

If your command line is

java Main

Then args contains zero elements and so when you access args[0] you get ArrayIndexOutOfBoundsException because args contains no elements so you can't access the first element because it doesn't exist.

Note that it is usually a good idea to first check how many elements args contains because, as you have seen, it is quite easy to launch your java program without the required number of arguments.

args.length

will return the number of elements in args.

huangapple
  • 本文由 发表于 2020年10月5日 14:48:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64203634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定