1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Java arrays

Discussion in 'Java' started by cyrow, Mar 25, 2008.

  1. cyrow

    cyrow New Member

    Joined:
    Nov 19, 2007
    Messages:
    21
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    class Test{
    	public static void main(String[] args){
    		int x=0;
    		int [] num = {1,1,3,3,3,3};
    		int [] a = new int [4];
    		
    	for(int i = 0; i < num.length-1; i++){
    	  x  =++num[i];
    	  a[i++] = x;
    		System.out.println("num :"+ i+"  " + x);
    	}
    	
    	
    	for (int j = 0; j< a.length; j++){
    		System.out.println(a[j]);
    	}
      }//end main
    }//end class
    
    /*
    num :1 2
    num :3 4
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Test.main(Love.java:10)

    Process completed.*/

    Problem
    I am going trought the array and counting all the elements which are the same. The answer given above is correct, 1 one occurs twice an 3 occurs 4 times. Why I am getting an out of bounds error?
     
  2. harikrishna_sit

    harikrishna_sit New Member

    Joined:
    Jan 24, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student(MCA)
    Location:
    Hyderabad,AP,India
    I could not find your logic correct. But I can say the reason for the exception. In the first for loop you are incrementing i value twice per iteration. So in the 3rd iteration i value will be 4. But when you say a[i++]=x; it will be a[4]=x; But the array a can have only 4 elements upto a[3]. That is the problem.
     

Share This Page