When i tried running this code I get this error..I dont know where i went wrong..
Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 0
args[0] != null
args
doesn't hold any element , so trying to access 0th will give you this
public class NewMain {
public static void main(String[] args) {
int argslen=args.length;
int argsValue[] = new int[argslen];
for (String i:args) {
int d = 0;
argsValue[d]=Integer.parseInt(i);
System.out.print(argsValue[d]+"\t");
}
}
}
args[0]
will never be null (when invoked from the command line) - but args.length
may be 0, in which case evaluating args[0]
will give you that exception, because there is no element 0 in the array. Just test for that:
if (args.length != 0)
{
n = Integer.parseInt(args[0])
}
As an aside, it's pretty odd to return a double
from fibo
- the normal Fibonacci sequence is defined in terms of integers (0, 1, 1, 2, 3, 5, 8 etc). If you want to scale it, I'd multiply it by your constant afterwards.
Are you supplying a command line argument when you run it?
if (args[0] != null)
n = Integer.parseInt(args[0]);
If you aren't then the above line will fail. You should check if args.length >= 1 before accessing args[0]
.
To check the args you should use args.length
- not reference the index explicitly
Here:
args[0]
On line 30
if (args[0] != null)
You have to pass an argument.
args[0]
Tries to access the first element in the args array, since which is filled from the command line arguments. If you don't pass any arguments that array is empty and trying to access an non existing element in an array gives that exception.
You have to learn to read the exception stacktrace. They seem meaningless at first, but once you know how to read it, they are very helpful. Here's yours:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at numericalComputatio.fibo.main(fibo.java:30)
It reads like this:
public static void main
methodjava.lang.ArrayIndexOutOfBoundsException: 0
which means there there is an array involved and the index tried to be access as 0 ( the first element ) that gives you a good clue of what's going on.fibo.java:30
This is also very helpful specially when you have that source file at hand, and can look directly at that line number. I hope this helps.