[英]Why do I get an 'ArrayIndexOutOfBoundsException' error?
I'm new to Java programming. 我是Java编程的新手。
Can someone assist me with the following code: 有人可以通过以下代码为我提供帮助:
public class RandomSeq { public static void main(String[] args) { // command-line argument 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()); } } }
I receive the following error message when trying to compile: 尝试编译时收到以下错误消息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Thank you in advance. 先感谢您。
[1] I use a 64-bit Java 8 (Update 25) SE implementation, using a 64-bit Eclipse IDE for Java Developers (v. 4.4.1). [1]我使用64位Java 8(更新25)SE实现,并使用针对Java开发人员的64位Eclipse IDE(4.4.1版)。
If you run your main()
without giving argument list( String[] args
) it will take args
as empty. 如果运行
main()
而不给出参数list( String[] args
),它将args
设为空。
So, the index 0
is not a valid index, since args
is empty. 因此,索引
0
不是有效索引,因为args
为空。
int N =Integer.parseInt(args[0]);// this cause ArrayIndexOutOfBoundsException
How to set argument for main()
in Eclipse.? 如何在Eclipse中为
main()
设置参数? Read from here . 从这里读 。
it's because args is empty : 这是因为args为空:
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");
}
}
}
Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run
确保在运行配置下的“主要”选项卡下选择了正确的项目名称及其主要方法
Its because You're not passing any Value So args[] is Empty.. 这是因为您没有传递任何值,所以args []为空。
When You are using Eclipse, go to Run->Run Configuration-> Arguments
, Pass some value. 使用Eclipse时,请转到
Run->Run Configuration-> Arguments
,传递一些值。
Your code runs perfectly fine..!! 您的代码运行得很好.. !!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.