Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

java - How do I swap two integers in an array, where my method takes in two integers and an array from main?

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;
}

My code yields

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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] + " ");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...