Merging two arrays in java

Discussion in 'Java' started by cyrow, Apr 2, 2008.

  1. cyrow

    cyrow New Member

    Joined:
    Nov 19, 2007
    Messages:
    21
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    
    
    class Merge{
    	public static void main(String[] args){
    		int[]A = {1,2,};
    		int[]B = {7,8,9};
    		int[]C = new int[A.length + B.length];
    		
    		int aIndex = 0;
    		int aCount = A.length;
    		int cIndex = C.length;
    		
    		
    		while (aIndex < aCount){
    			if(A[aIndex] < B[aIndex]){
    				C[aIndex]= A[aIndex];
    				}
    			aIndex++;
    		
    		}//end while
    		
    		for(int bIndex = 1; bIndex < cIndex ; bIndex++){
    			C[bIndex] = B[bIndex];//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
        								//at Merge.main(Merge.java:23)
    	
    		}
    		
    		for (int i = 0; i < C.length; i++){
    			System.out.println(C[i]);
    		}
    		
    	}//end main
    }//end class
    
    
    I am trying to merge the two arrays identified above. I am getting an outofbounds errors, what might the problem be?
     
  2. lokesh_goyal

    lokesh_goyal New Member

    Joined:
    Apr 2, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    after this code...
    while (aIndex < aCount){
    if(A[aIndex] < B[aIndex]){
    C[aIndex]= A[aIndex];
    }
    aIndex++;

    }//end while
    indexing in array c is 1 size more than size of array
    so u need to first decrease by 1, and then ur program will never shows exception
    try it...
    Lokesh
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice