Reputation: 23
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
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
Reputation: 29693
Your array args
is empty.
int OddLimit = Integer.parseInt("100");
hardcode number, or pass it from command line
Upvotes: 0
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
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
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