-1

I'm running into a little trouble understanding how I can initialize an array with the values that are listed in the notes. How would I be able to set up array and proceed to use the code below to properly return the respective output.

This question varies from the duplicate linked because it is asking how to initialize the array within a local method.

/*Write a method that reverses the sequence of elements in an array. For example, if
you call the method with the array 
    1  4  9  16  9  7  4  9  11 
then the array is changed to 
    11  9  4  7  9  16  9  4  1*/

public static void reverse(int[] array) { 
        for (int i = 0; i < array.length / 2; i++) { 
            int temp = array[i]; 
            array[i] = array[array.length - 1 - i]; 
            array[array.length - 1 - i] = temp; 

        } 
    } 
  • 3
    `int[] array = { 1, 4, 9, 16, 9, 7, 4, 9, 11 });` -> `reverse(array);`? – nbokmans Feb 06 '18 at 14:51
  • @nbokmans The method returns void, so can't assign it to a variable. – Morgan Feb 06 '18 at 14:53
  • @nbokmans the assignment is still there ;) – Thomas Feb 06 '18 at 14:55
  • My bad @Thomas - not sure how I messed that up twice. Btw there is an extra parenthesis in the first code block of my comment but it's been five minutes so I can't update my comment. – nbokmans Feb 06 '18 at 14:56
  • 1
    Hint: you are expected to do serious research prior posting questions. And it is very safe to assume that *anything* you come up asking as newbie ... was asked before. Countless times. – GhostCat Feb 06 '18 at 14:59

1 Answers1

1

First you need to define an array and to initialize it with the given values. This could be done directly on the declaration of the variable. Then you need to pass the reference to the reverse method.

public static void main(String[] args) {

    int[] array = {1, 4, 9, 16, 9, 7, 4, 9, 11};
    reverse(array);

    Arrays
        .stream(array)
        .forEach(System.out::println);
}

private static void reverse(int[] array) {
    for (int i = 0; i < array.length / 2; i++) {
        int temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = temp;

    }
}

You can find more information about how to initialize an array here: http://www.baeldung.com/java-initialize-array

dbl
  • 1,109
  • 9
  • 17
  • it was done by the time you've added the comment so it's irrelevant. – dbl Feb 06 '18 at 15:01
  • I seem to be getting a "Duplicate local variable array" error – Abubakkar Siddique Feb 06 '18 at 15:19
  • You have defined a variable with name "array" more than one times in a single code scope. A definition is: [TYPE] [NAME] (= [VALUE]); Use search feature and see if there is more than one "array = value;". I've edited the answer with the code I've tested on my machine. – dbl Feb 06 '18 at 15:22