-4

This is not a homework question. It is one of my practices. Please help me understand where i did wrong. The original was static void changeArray, but i changed it to static int changeArray and inserted a return statement at the end, but it still won't update the main code.

public class testing{

/*
 * Change the method to also update the key at the main
 */

static int changeArray(int key, int array[]){

    key = key + 7;

    for (int i = 0; i < array.length; i++){
        array[i] = array[i] + key;
    }

    System.out.println("*At changeArray *");
    System.out.println("The key is: "+ key);
    return key; 

}

static void printArray(int array[]){

    System.out.print("[ ");
    for (int element:array){
        System.out.print(element + " ");
    }
    System.out.println("]");
}

public static void main(String[] args){
    int key = 5;
    int[] array = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};

    System.out.println("*At the main *");
    System.out.println("The key is: "+ key);

    printArray(array);
    changeArray(key, array); 

    System.out.println("*At the main *");
    System.out.println("The key is: "+ key); <--- (this is supposed to be 12 after the method is called, but it keeps printing out 5)
    printArray(array);
}

}

PiP
  • 11
  • 1
  • You are not assigning the return value of `changeArrray()` to anything. It should be assigned to `key` in your main method. – Bethany Louise Apr 27 '16 at 00:26

1 Answers1

0

You need to set the key variable in your main method to the return from changeArray. Since key is a primitive type, changing it in your changeArray method won't change it in your main method. Change your changeArray call to the following. key = changeArray(key, array)