loop is cut one element of the array

Posted by Walaa on Stack Overflow See other posts from Stack Overflow or by Walaa
Published on 2013-11-12T09:32:34Z Indexed on 2013/11/12 9:53 UTC
Read the original article Hit count: 187

Filed under:
|

The problem is :

Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents.

My code :

import java.util.*;

public class Q1 {
  static Scanner scan = new Scanner (System.in);

  public static void main(String args [] ) {
    int num;
    int i = 0;
    System.out.println("Enter a number :");
    num = scan.nextInt();

    double [] a=new double[num];
    a[0]= num ;

    for ( ;i<=a.length-1 ; i++) {
      a[i+1] = Math.pow(2,a[i]);

      System.out.println((int)(a[i]) );
    }
  }
}

The error is :

   ----jGRASP exec: java Q1

Enter a number :
4
4
16
65536
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Q1.main(Q1.java:16)

 ----jGRASP wedge2: exit code for process is 1.

why it says that? And the number by user printed twice!

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays