简体   繁体   中英

Bubble Sort ArrayIndexOutOfBounds in Java

for(i=0;i<=4;i++)
            {
                for(j=0;j<=4;j++)
                {
                    if(hand[j] > hand[j+1])
                    {
                        temp = hand[j];
                        hand[j] = hand[j+1];
                        hand[j+1] = temp;
                    }
                }
            }

When I try to run this bubble sorting program, there's an ArrayIndexOutOfBounds Exception. Why? And how do I fix it?

You are accessing hand[] from index 0 to 5 (since it is j+1 ). Size of hand[] must be at least 6 for you to be able to do it. In your case, it is not, hence the error.

发生这种情况的原因是,您的数组大小为5,因此范围是0-4,而您尝试在最后一次迭代中从hand[j+1]中获取值,这意味着hand [5]会产生此异常。

As everyone else said, when you have 5 elements in the array you can only access indices 0 to 4. As far as fixing goes, it should be:

for(i=0;i<4;i++)
{
    for(j=0;j<4-i;j++)
    {
        if(hand[j] > hand[j+1])
        {
            temp = hand[j];
            hand[j] = hand[j+1];
            hand[j+1] = temp;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM