java 如何交换数组中的两个整数,其中我的方法从 main 接收两个整数和一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13056670/
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
How do I swap two integers in an array, where my method takes in two integers and an array from main?
提问by perldog93
I call my swap method in main, but it doesn't change anything. What am I doing wrong?
我在 main 中调用了我的交换方法,但它没有改变任何东西。我究竟做错了什么?
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;
}
My code yields
我的代码产生
0, 1, 2, 3,...19
in normal ascending order, where I want it to swap the 4th and 15th element.
按正常升序排列,我希望它交换第 4 个和第 15 个元素。
回答by Rohit Jain
Move the method call: -
移动方法调用:-
swapper(3, 14, mainArr);
outside your for loop. Since, if your loop runs even
number of times, it will not affect
the array.
在你的 for 循环之外。因为,如果您的循环运行even
多次,则不会影响数组。
Also, you need to initialize your array first, before actually swapping the elements. That you would need to do before invoking swapper
.
此外,在实际交换元素之前,您需要先初始化数组。在调用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] + " ");
}
回答by Woot4Moo
Writing the code as so:
编写代码如下:
int mainArr[] = new int[20];
for(int i =0; i <mainArr.length;i++)
{
mainArr[i]=i;
}
swapper(3,14,mainArr);
will resolve the issue. The problem was you happened to be calling swap an even number of times, so it had a total effect of nothing.
将解决问题。问题是你碰巧调用了 swap 偶数次,所以它完全没有效果。
回答by Bohemian
You are calling swapper the same number of times as there are elements in your array.
您调用 swapper 的次数与数组中的元素次数相同。
- If the array has a even length, nothing will change
- If the array has a odd length, it will change
- 如果数组的长度为偶数,则什么都不会改变
- 如果数组的长度为奇数,它将改变
回答by Pradeep Ghimire
public class swapInt
{
public static void main(String args[])
{
swap(new int[]{2,3,5,6,8},1,3);
}
public static void swap(int[]a,int i,int j)
{
int temp=a[i];
a[i]= a[j];
a[j]=temp;
for(int b=0;b<a.length;b++)
{
System.out.println(a[b]);
}
}
}