How do I return an array after it has been swapped?

So I have my main method which is supposed to have an array of 1-20 print, and then I am supposed to pass that array in a loop for every even number occurrence. The swap method will switch the even number in the array with the next number... so in the array [1, 2, 3, 4, 5,..], 2 and 3 would switch and 4 and 5 would switch.

Here is the main method:

public class Lab_01_Tester {

public static void main (String[] args) throws FileNotFoundException
{
    PrintWriter writer = new PrintWriter("Lab_01_nums.txt");
    int[] randArray  = Lab_01_ArrayUtilities.buildIntArray(20, 10, 29);

    String randArrayString = Arrays.toString(randArray);

    writer.write(randArrayString);
    System.out.print(randArrayString);

    writer.close();

    for (int i = 0; i < randArray.length - 1; i++)
    {
        if (randArray[i] % 2 == 0)
        {
            Lab_01_ArrayUtilities.swap (randArray, i, i + 1);
            i = i +1;
        }

        else;

    }
    System.out.println();
    System.out.print(randArrayString);

}

}

And here is the swap method that randArray is getting passed to:

public static int[] swap (int[] randArray, int i, int j)
{
    int temp = randArray[i];
    randArray[i] = randArray[j];
    randArray[j] = temp;

    return randArray;
}

My problem is that when the array is passed back, it is unchanged

Jon Skeet
people
quotationmark

You don't need to return anything (assuming you change the method signature to return void) - the elements of the array have been swapped in-place.

For example:

int[] array = { 3, 5, 4 };
swap(array, 0, 2);
System.out.println(array[0]); // 4
System.out.println(array[2]); // 3

This is your actual problem:

System.out.print(randArrayString);

You haven't changed randArrayString since you last printed it - so no wonder it's printing the same value. You just need to add this line again, just before printing it out:

randArrayString = Arrays.toString(randArray);

people

See more on this question at Stackoverflow