Java数组顺序反转 [英] Java array order reversing

查看:71
本文介绍了Java数组顺序反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习数组,而我正在尝试颠倒数组中的顺序。这是到目前为止的方法,但仅适用于数组中值的前一半。我在做什么错?

Im learning arrays and Im trying to reverse the order in an array. This is the method I've got this far but it's only working for the first half of the values in the array. What am I doing wrong?

public static void reverse(int[] anArray)
{
    int[] a = anArray ;
    for (int j = 0; j <= (a.length - 1); j++ )
    {
        anArray[j] = a[(anArray.length - j - 1)];
    }
}


推荐答案

您需要进行临时定位才能进行交换。这段代码将数组的末尾写到前面,但是到您写数组的末尾时,值的前一半已经丢失了。

You need to make a temporary location in order to do the swap. This code write the end of the array to the front, but by the time you get to writing the end of the array, the first half of the values have already been lost.

public static void reverse(int[] a)
{
    int l = a.length;
    for (int j = 0; j < l / 2; j++)
    {
        int temp = a[j];
        a[j] = a[l - j - 1];
        a[l - j - 1] = temp;
    }
}

此外,您正在递增 j 两次。 for循环定义的最后一部分在每个循环之间进行递增。您无需在循环块内手动进行操作。

Additionally, you are incrementing j twice. The last part of the for loop definition does the increment between each loop. You don't need to do it manually inside the loop block.

这篇关于Java数组顺序反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆