0

so im done with the whole thing and i compile it when i ran it it had a error for said: arrayindexexception and i try looking for my mistake and i could not find it so i need someone to see if they can help me

public class Merging
{

    public static int[] merge(int[] arrA, int[] arrB)
    {
        int[] sum = new int[arrA.length + arrB.length];
        int i = 0, j = 0, k = 0;

        while ( i < arrA.length && j < arrB.length)
        {
            if(arrA[i] < arrB[j])
            {
                sum[k] = arrA[i];
                i++;
                k++;
            }else
                sum[k] = arrB[i];
                j++;
                k++;
        }
        return sum;

    }  
    public static void main(String[] args)
    {
        int a = (int)(Math.random() * (50-20+1)+20);
        int b = (int)(Math.random() * (50-20+1)+20);

        int[] a1 = new int[a];
        int[] a2 = new int[b];

        int i = 0;
        while(i < a1.length && 1 < a2.length)
        {
            a1[i] = (int) (Math.random() * (150-20+1)+20);
            a2[i] = (int) (Math.random() * (150-20+1)+20);
            i++;
        }

        for(int j = 0; j < a1.length; j++)
        {
        System.out.print(a1[j]);
        }
        System.out.println();
        for(int k = 0; k < a2.length; k++)
        {
        System.out.print(a1[k]);
        }
        System.out.println();
        System.out.print(merge(a1,a2));             
    }
}
1
  • 2
    Be specific. What exactly was the error, and where exactly was it occurring? Commented Nov 14, 2014 at 2:33

3 Answers 3

1

Two errors.

1.) Change from 1 < a2.length to i < a2.length

 while (i < a1.length && i < a2.length) {
            a1[i] = (int) (Math.random() * (150 - 20 + 1) + 20);
            a2[i] = (int) (Math.random() * (150 - 20 + 1) + 20);
            i++;
        }

2.) Change from System.out.print(a1[k]); to System.out.print(a2[k]);

 for (int k = 0 ; k < a2.length ; k++) {
            System.out.print(a2[k]);
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Yea i just didnt check my work well, because i had to turn it in before 9pm or you lose a point, so i rush and did not check it. Thanks
@chilithewilly pls accept/upvote the answer if it solves your purpose
0

In your while loop

while(i < a1.length && 1 < a2.length)

the "1" should be an "i"

Comments

0

One of your problems is here

for(int k = 0; k < a2.length; k++)
{
    System.out.print(a1[k]);
}

You're iterating through a1, but your index goes to the length of a2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.