Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Merging two arrays in java (http://www.go4expert.com/forums/merging-arrays-java-t9716/)

cyrow 2Apr2008 22:39

Merging two arrays in java
 
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?

lokesh_goyal 2Apr2012 13:16

Re: Merging two arrays in java
 
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


All times are GMT +5.5. The time now is 11:43.