Swapping Array indicies by calling a method

mightymorphinParkRanger :

Solved (code is updated)

I'm having trouble finding out why my code is not working. I have the method that swaps the values and as far as I'm aware, it should be working. I've looked at this link here but I can't tell where I went wrong (I know it's not java, but the concept is the same) https://www.kirupa.com/html5/swapping_items_array_js.htm

Here is an example output of the code:

4
1
1
1
1
Provide two indicies to swap
0
2
4
1
1
1
1

/

import java.util.Scanner;
public class Test100 {

    public static void main(String[] args) {
        Scanner arrayScan = new Scanner(System.in);
        int[] values = new int[5];

        values[0] = 4;
        values[1] = 1;
        values[2] = 1;
        values[3] = 1;
        values[4] = 1;

        System.out.println(values[0]);
        System.out.println(values[1]);
        System.out.println(values[2]);
        System.out.println(values[3]);
        System.out.println(values[4]);

//      provide user input to choose values to swap
        System.out.println("Provide two indicies to swap");
        int userInput1 = Integer.valueOf(arrayScan.nextLine());
        int userInput2 = Integer.valueOf(arrayScan.nextLine());

        int inputArray1 = values[userInput1];
        int inputArray2 = values[userInput2];


        valSwap(values, userInput1, userInput2);    

        System.out.println(values[0]);
        System.out.println(values[1]);
        System.out.println(values[2]);
        System.out.println(values[3]);
        System.out.println(values[4]);

    }

    public static void valSwap(int[] array, int input1, int input2) {
    int swapper = array[input1];
    array[input1] = array[input2];
    array[input2] = swapper;

    }
}

I realized that I originally had been putting in the array indicie within my argument used inside the method when I called it. I changed that over to just the value the user entered because I realized I altered the method based off of what user @Joop Eggen had mentioned. I modified my method to match that and then altered the arguments when I called it.

Joop Eggen :

Java was designed so that f(x) never changes a passed variable x. That is the (object) value of the variable is passed, not an "address" (reference) of some variable.

So swapping array positions:

void swap(int[] array, int index1, int index2) {
    int temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
}

So swap(values, 2, 3) will never change values to point to null or an other array, but the array object may internally be changed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=318583&siteId=1