如何在数组中交换两个整数,其中我的方法采用两个整数和一个来自main的数组? [英] How do I swap two integers in an array, where my method takes in two integers and an array from main?

查看:102
本文介绍了如何在数组中交换两个整数,其中我的方法采用两个整数和一个来自main的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在main中调用我的swap方法,但它不会改变任何东西。我做错了什么?

I call my swap method in main, but it doesn't change anything. What am I doing wrong?

public static void main(String[] args){


    int mainArr[] = new int[20];

    for(int i = 0; i<mainArr.length; i++){
    swapper(3, 14, mainArr);
    System.out.print(i + mainArr[i] + " ");
    }
}


public static void swapper (int a, int b, int[] mainArr){
    int t = mainArr[a];
    mainArr[a] = mainArr[b];
    mainArr[b] = t;
}

我的代码产量

0, 1,  2, 3,...19 

按正常的升序排列,我希望它交换第4和第15个元素。

in normal ascending order, where I want it to swap the 4th and 15th element.

推荐答案

移动方法调用: -

Move the method call: -

swapper(3, 14, mainArr);

在你的for循环之外。因为,如果您的循环运行甚至次数,它将不会影响
数组。

outside your for loop. Since, if your loop runs even number of times, it will not affect the array.

此外,在实际交换元素之前,需要先初始化数组。在调用 swapper 之前你需要做的。

Also, you need to initialize your array first, before actually swapping the elements. That you would need to do before invoking swapper.

for(int i = 0; i<mainArr.length; i++){
    mainArr[i] = i;
}

swapper(3, 14, mainArr);

for(int i = 0; i<mainArr.length; i++){
    System.out.print(i + mainArr[i] + " ");
}

这篇关于如何在数组中交换两个整数,其中我的方法采用两个整数和一个来自main的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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