完成该交换整数数组的上半年和下半年的方法 [英] complete a method that swaps the first and second half of an array of integers

查看:80
本文介绍了完成该交换整数数组的上半年和下半年的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到一个出界失误的,每当我尝试运行我的code。有谁知道什么是错呢?我似乎无法弄清楚。

 公共类被囚{    / **
    这种方法交换给定数组的第一和第二的一半。
    @参数值的数组
     * /    公共无效swapFirstAndSecondHalf(INT []值){
        //你在这里工作        INT [] =首新INT [values​​.length / 2];
        INT []第二=新INT [values​​.length / 2];
        的for(int i = 0; I< values​​.length / 2;我++){
            第二[I] =值[I]
        }
        对于(INT J = values​​.length / 2; J< values​​.length; J ++){
            第一[J] =值[J]。
        }
        对于(INT K = 0; K< values​​.length / 2; k ++){
            值[K] =第[K];
        }
        对于(INT L = values​​.length / 2; L< values​​.length,L ++){
            值[1] =第二[L];
        }
    }    //此方法用于检查您的工作
    公众诠释[]检查(INT []值){
        swapFirstAndSecondHalf(值);
        返回值;
    }
}


解决方案

  INT [] =首新INT [values​​.length / 2];

所以指数 [0..values​​.length / 2 - 1。有效期为第一

 的for(int J = values​​.length / 2; J< values​​.length; J ++)
{
    第一[J] =值[J]。
}

因此​​,与Ĵ values​​.length / 2 的第一个值,它已经出界。

您需要在实践调试,把一个破发点,并跟踪code,因为它执行。

I keep getting an out of bounds error whenever i try to run my code. Does anyone know what is wrong with it? I can't seem to figure it out.

public class Swapper{

    /**
    This method swaps the first and second half of the given array.
    @param values an array
     */

    public void swapFirstAndSecondHalf(int[] values) {
        // your work here

        int[] first = new int[values.length/2];
        int[] second = new int[values.length/2];
        for(int i = 0; i < values.length / 2; i++) {
            second[i] = values[i];
        }
        for (int j = values.length / 2; j < values.length; j++) {
            first[j] = values[j];
        }
        for(int k = 0; k < values.length / 2; k++) {
            values[k] = first[k];
        }
        for(int l = values.length / 2; l < values.length; l++) {
            values[l] = second[l];
        }
    }

    // This method is used to check your work
    public int[] check(int[] values) {
        swapFirstAndSecondHalf(values);
        return values;
    }
}

解决方案

int[] first = new int[values.length/2];

So indexes [0..values.length/2 - 1] are valid for first.

for (int j=values.length/2; j<values.length; j++)
{
    first[j] = values[j];
}

So with the first value of j being values.length/2, it's already out of bounds.

You need to practice debugging, placing a break point and tracing the code as it executes.

这篇关于完成该交换整数数组的上半年和下半年的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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