0

I wrote the code for Fibonacci series but I get error ArrayIndexOutofBoundsException. Can you please help me find source of this exception?

class Fib {
    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        System.out.println("Fibonacci Series");
        int f1, f2 = 0, f3 = 1;
        for (int i = 1; i <= num; i++) {
            System.out.print(" " + f3 + " ");
            f1 = f2;
            f2 = f3;
            f3 = f1 + f2;
        }
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • When you get exception and you want to ask others about it, beside code which throws this exception post also its [stacktrace](http://stackoverflow.com/a/3988794/1393766). – Pshemo Mar 31 '14 at 18:32

2 Answers2

4

You didn't supply any command-line arguments to your program, so args is a zero-length array. Any access of a zero-length array will result in an ArrayIndexOutOfBoundsException.

Check if args.length is at least 1 before accessing the first element (of index 0).

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

I haven't tested the code you submitted but here is couple of clues:

  • You are executing the application without any argument.
  • You should first check if the arguments length is greater than 0.
  • Before parsing the input argument, do either check if it is a number or surround the parsing with a try/catch.

I hope this helps.

Good luck!

kazbeel
  • 1,378
  • 19
  • 40