Capt'n Brian
Capt'n Brian

Reputation: 23

Getting an ArrayIndexOutOfBoundsException

I have this code :

public class OddSum1 {
   public OddSum1() {
   }
   public static void main(String[] args) {

   int OddLimit = Integer.parseInt(args[0]);
   int sum = 0;

   for (int i = 1; i <= OddLimit; i += 2) {
     sum += i;
   }

   System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum);

   }    
}

Whenever I run it I get this error:

java.lang.ArrayIndexOutOfBoundsException: 0
    at OddSum1.main(OddSum1.java:7)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

It's supposed to prompt user for a number and then sums the odd number from 1 to the number entered, I'm guessing it's a problem with this int OddLimit = Integer.parseInt(args[0]);

but I just don't know how to fix it, any help would be awesome.

Upvotes: 1

Views: 1331

Answers (5)

mehtabsinghmann
mehtabsinghmann

Reputation: 66

You can take either of the two approaches from below :

Approach 1 : You can specify the oddLimit by passing it as an argument to the main method as :

Code :

public class OddSum1 {
public OddSum1() {
}
public static void main(String[] args) {
int OddLimit = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 1; i <= OddLimit; i += 2)
sum += i;
System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum);
}    
}

To compile and run the code :

javac OddSum1.java

java OddSum1 20

Approach 2 : Read the OddLimit interactively from the prompt

Code:

public class OddSum1 {
public OddSum1() {
}
public static void main(String[] args) {

int OddLimit = Integer.parseInt(System.console().readLine());
int sum = 0;

for (int i = 1; i <= OddLimit; i += 2)
sum += i;

System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum);

}
}

Upvotes: 1

Ilya
Ilya

Reputation: 29693

Your array args is empty.

int OddLimit = Integer.parseInt("100");  

hardcode number, or pass it from command line

Upvotes: 0

Voicu
Voicu

Reputation: 17850

If using Eclipse, choose from the top menu Run->Run... and under the Arguments tab provide a number for the Program arguments.

Upvotes: 0

maba
maba

Reputation: 48065

It will not prompt you for input. You will have to add the input to the command line.

java OddSum1 5

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240900

It's supposed to prompt user for a

You need to pass arguments to main, Command line argument and then change index to 0

for example:

$java YourMainClass 5

Upvotes: 4

Related Questions