I'm new to Java programming.
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).
If you run your main()
without giving argument list( String[] args
) it will take args
as empty.
So, the index 0
is not a valid index, since args
is empty.
int N =Integer.parseInt(args[0]);// this cause ArrayIndexOutOfBoundsException
How to set argument for main()
in Eclipse.? Read from here .
it's because args is empty :
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..
When You are using Eclipse, go to Run->Run Configuration-> Arguments
, Pass some value.
Your code runs perfectly fine..!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.