交换方法的问题-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
Trouble with swap method-java
提问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 swap
method looks good, but it is never called. It looks like it should be called from main
. The main
method is static, and you don't have (or need) an instance of test
, so include static
in your swap
method. Add the call to swap
in your main
method.
您的swap
方法看起来不错,但从未调用过。看起来应该从main
. 该main
方法是静态的,您没有(或不需要) 的实例test
,因此请包含static
在您的swap
方法中。swap
在您的main
方法中添加调用。
Additionally, you don't use i
and j
in swap
-- replace 2
with i
and 4
with j
. Also, you never use char[] intArray
, which is declared as an instance variable; it can be safely removed.
此外,你不使用i
,并j
在swap
-替换2
用i
和4
用j
。此外,您永远不会使用char[] intArray
, 声明为实例变量;它可以安全地移除。
回答by Tom Hawtin - tackline
You never actually call the swap
method, so add to your main
method:
你从来没有真正调用过这个swap
方法,所以添加到你的main
方法中:
new test().swap(-1, -1, intArray);
Or:
或者:
test testObj = new test();
testObj.swap(-1, -1, intArray);
Sending a primitive array to PrintWriter
will 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));