Results 1 to 4 of 4
  1. #1
    leonard is offline Member
    Join Date
    Jul 2007
    Posts
    43
    Rep Power
    0

    Default help with simple java program

    I did a simple program but I have a problem
    this is the code
    Java Code:
    public class Test
    {
    private static int[] numbers=new int[4];
    public static void main( String args[] )
    {
    
      	for (int i = 1;i<=4;i++)  {
    		numbers[i]=1;
    	}
    
    }
    
    }
    and this exception appears:
    Java Code:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    	at Test.main(PayrollProgramExecute.java:16)
    any ideas?

  2. #2
    neel5_kumar is offline Member
    Join Date
    Jul 2007
    Posts
    1
    Rep Power
    0

    Default

    try either
    (int i=0;i<4;i++)//as index starts with 0
    or
    (int i=0;i<numbers.length;i++)//much better

  3. #3
    mirage_87 is offline Member
    Join Date
    Jul 2007
    Posts
    8
    Rep Power
    0

    Default

    in an array the indexing begins from 0 and not from one..
    so the flaw in yr program is that u started with one and went till 4
    instead u shld have done
    for (int i = 0;i<=3;i++)
    this is because no element numbers[4] exist as the index is only from 0 to 3.....that's why the error.

    private static int[] numbers=new int[4]; means u r creatin an array with four elements with index 0,1,2,3 and not 4.............
    i guess you got the point...........

  4. #4
    Swamipsn is offline Member
    Join Date
    Jul 2007
    Posts
    74
    Rep Power
    0

    Smile Simple reason

    public class ex1
    {
    private static int[] numbers=new int[4];
    public static void main( String args[] )
    {

    for (int i = 0;i<=3;i++) {
    numbers[i]=1;
    }

    }

    }

    Problem is you are trying to access numbers[4] obviously it has number[0]
    to numbers[3], not numbers[4]

Similar Threads

  1. Replies: 0
    Last Post: 04-04-2008, 03:40 PM
  2. Peculiarty in code of simple program...
    By Kreuz14 in forum New To Java
    Replies: 4
    Last Post: 01-23-2008, 04:27 AM
  3. Simple java
    By abhiN in forum New To Java
    Replies: 1
    Last Post: 01-16-2008, 11:13 AM
  4. Replies: 0
    Last Post: 10-04-2007, 10:33 PM
  5. help with simple program in java
    By katie in forum New To Java
    Replies: 2
    Last Post: 08-06-2007, 09:03 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •