为什么我会收到'ArrayIndexOutOfBoundsException'错误?
我是Java编程新手。为什么我会收到'ArrayIndexOutOfBoundsException'错误?
有人能帮助我用下面的代码:
public class RandomSeq {
\t public static void main(String[] args) {
\t \t // command-line argument
\t \t int N = Integer.parseInt(args[0]);
\t \t // generate and print N numbers between 0 and 1
\t \t for (int i = 0; i < N; i++) {
\t \t \t System.out.println(Math.random());
\t \t }
\t }
}
我收到在编译的时候出现以下错误信息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
预先感谢您。
[1]我使用64位Java 8(更新25)SE实现,使用64位Eclipse IDE for Java Developers(v。4.4.1)。
Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run
确保合适的项目名称和它的下运行配置
解决。谢谢。 :) – User 2014-10-17 05:20:10
如果您在未给出参数列表(String[] args
)的情况下运行main()
,则会将args
设为空。
因此,索引0
不是有效索引,因为args
为空。
int N =Integer.parseInt(args[0]);// this cause ArrayIndexOutOfBoundsException
如何在Eclipse中为main()
设置参数。 Read from here。
解决。非常感谢。 :) – User 2014-10-17 05:31:15
@欢迎使用者 – 2014-10-17 05:32:20
这是因为参数表是空的:
public class RandomSeq {
public static void main(String[] args) {
// command-line argument
if (args.length > 0) {
int N = Integer.parseInt(args[0]);
// generate and print N numbers between 0 and 1
for (int i = 0; i < N; i++) {
System.out.println(Math.random());
}
}
else {
System.out.println("args is empty");
}
}
}
其“主”选项卡下选择的主要方法,因为你'没有传递任何值所以args []是空的。
当您使用Eclipse时,请转至Run->Run Configuration-> Arguments
,传递一些值。
你的代码运行完好.. ..!
你如何启动应用程序? – 2014-10-17 04:55:46