0

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).

User
  • 11
  • 1

4 Answers4

3

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.

Community
  • 1
  • 1
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

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");
        }
    }
}
ReZa
  • 1,273
  • 2
  • 18
  • 33
0

Run-> Run Configurations->Arguments->Enter your arguments separated by space->Apply->Run

Ensure that the right project name and it's main method are selected under "the Main" tab under run configurations

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

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..!!

SonalPM
  • 1,317
  • 8
  • 17