Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change an array in a different method?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading