控制台显示线程中的异常 "main" java.lang.ArrayIndexOutOfBounds异常:0



当我尝试运行和编译代码时,控制台显示:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at FactorialProgram5.main(FactorialProgram5.java:9)

我不明白它为什么这么做,因为我做的其他代码都在工作。

这是我的代码:

import java.util.Scanner;
public class FactorialProgram5 {
public static void main(String args[]) {
long n;
long fact = 1;
n = Long.parseLong(args[0]);
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.print("fact=" + fact);
}
}

如果在执行程序时没有传递参数,args[0]会尝试检索参数数组的第一个值,但如果数组为空(因为没有传递值(,则会引发此类异常。

ArrayIndexOutOfBoundsException: 0表示您试图访问数组中不存在的位置。如果您尝试访问位置0,但失败是因为数组为空。

因为当你运行程序时,你没有向它传递参数。你的args数组是空的,当你试图获得空数组的第0个元素时,你会得到IndexOutOfBoundException以下行需要参数

n=Long.parseLong(args[0]);

尝试通过向传递参数来运行程序

相关内容

最新更新