交换方法的问题-java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16181346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:08:14  来源:igfitidea点击:

Trouble with swap method-java

javaarraysindexingswap

提问by ashley

Hello everyone I am currently creating a program where I want to swap index 2 and 4. I have the code completed however I do not receive an output and when I run the program I do not receive an error

大家好,我目前正在创建一个程序,我想在其中交换索引 2 和 4。我已经完成了代码,但是我没有收到输出,当我运行该程序时,我没有收到错误

Here is what I have so fa:

这是我所拥有的:

public class test {
    public static void main(String[] args) {
        int[] intArray = {2,4,6,8,10};
    }

    char[] intArray;
    void swap(int i, int j, int[] arr) {
        int t = arr[2];
        arr[2] = arr[4];
        arr[4] = t;
        System.out.println(intArray);
    }
}

回答by Reimeus

You never call swap:

你从不打电话swap

public static void main(String[] args) {
   int[] intArray = { 2, 4, 6, 8, 10 };
   new test().swap(1, 2, intArray); // use local array
}

// char[] intArray; not needed

private void swap(int i, int j, int[] arr) {
   int t = arr[i];
   arr[i] = arr[j];
   arr[j] = t;
   System.out.println(Arrays.toString(arr)); // print array passed in
}

回答by rgettman

Your swapmethod looks good, but it is never called. It looks like it should be called from main. The mainmethod is static, and you don't have (or need) an instance of test, so include staticin your swapmethod. Add the call to swapin your mainmethod.

您的swap方法看起来不错,但从未调用过。看起来应该从main. 该main方法是静态的,您没有(或不需要) 的实例test,因此请包含static在您的swap方法中。swap在您的main方法中添加调用。

Additionally, you don't use iand jin swap-- replace 2with iand 4with j. Also, you never use char[] intArray, which is declared as an instance variable; it can be safely removed.

此外,你不使用i,并jswap-替换2i4j。此外,您永远不会使用char[] intArray, 声明为实例变量;它可以安全地移除。

回答by Tom Hawtin - tackline

You never actually call the swapmethod, so add to your mainmethod:

你从来没有真正调用过这个swap方法,所以添加到你的main方法中:

new test().swap(-1, -1, intArray);

Or:

或者:

test testObj = new test();
testObj.swap(-1, -1, intArray);

Sending a primitive array to PrintWriterwill just give the default output from Object.toString. To get the values of the elements of the array use Arrays.toString. So use:

将原始数组发送到PrintWriter只会从Object.toString. 要获取数组元素的值,请使用Arrays.toString. 所以使用:

System.out.println(java.util.Arrays.toString(intArray));