Home > Back-end >  How to change an array in a different method?
How to change an array in a different method?

Time:05-31

I wanted to have a method that makes an array and a method that changes the array (the 13 into a 6 and add 2 on the fourth item) and then catch both the changed and unchanged arrays in variables, but I can't seem to call the changed array in the main, without there being an error

public class ArrayFillApp {

    public static void main(String[] args) {
        ArrayFill arrayFill = new ArrayFill();
        arrayFill.makeArray();
        for(int value: arrayFill.makeArray()){
            System.out.println(value);
        }
    }
}

public class ArrayFill {

    public int[] makeArray(){
        int[] array = {
            6, 13, 34, -10, 15
        };
        return array;
    }

    public int[] changeArray(int[] array){
        array[1] = 6;
        array[3] = array[3]   2;
        int[] arrayCopy = new int[array.length];
        for (int value: array) {
            array[value] = arrayCopy[value];
        }
        return arrayCopy;
    }
}

CodePudding user response:

You could save the array with a local variable reference. Don't call makeArray twice. There's no need. Simply declare a local reference and assign it. Then pass that reference to the second method.

ArrayFill arrayFill = new ArrayFill();
int[] array = arrayFill.makeArray();
array = arrayFill.changeArray(array); // OR,
// arrayFill.changeArray(array); // It's the same array.
for(int value : array){
    System.out.println(value);
}

Also, in changeArray you don't need to copy the array.

public int[] changeArray(int[] array){
    array[1] = 6;
    array[3]  = 2;
    return array;
}

CodePudding user response:

Consider saving the output of your makeArray and changeArray into a couple of variables and utilizing clone if you do not want changeArray to modify the passed-in array (assuming that is the case since you are making a copy):

import java.util.Arrays;

public class ArrayFillApp {
    public static void main(String[] args) {
        ArrayFill arrayFill = new ArrayFill();
        int[] originalArray = arrayFill.makeArray();
        int[] changedArray = arrayFill.changeArray(originalArray);
        System.out.printf("originalArray: %s%n", Arrays.toString(originalArray));
        System.out.printf("changedArray: %s%n", Arrays.toString(changedArray));
    }
}

public class ArrayFill {
    public int[] makeArray() {
        return new int[]{6, 13, 34, -10, 15};
    }

    public int[] changeArray(int[] array) {
        int[] arrayCopy = array.clone();
        arrayCopy[1] = 6;
        arrayCopy[3]  = 2;
        return arrayCopy;
    }
}

Output:

originalArray: [6, 13, 34, -10, 15]
changedArray: [6, 6, 34, -8, 15]
  •  Tags:  
  • java
  • Related