-3

Surprisingly, I can't seem to find an answer to this anywhere.

I have initialized a new int array named "array" and done some things to it in a method named "reverse" and it returns array.length, how do I print the returned array in the main method and not the originally initialized array?

Here is my code, the for loop is what I am having problems with

public static void main(String[] args) 
{
    int array[] = new int [7];
    array[0] = 5 ;
    array[1] = 10;
    array[2] = 11;
    array[3] = 19;
    array[4] = 13;
    array[5] = 14;
    array[6] = 16;
         for(int i = 0; i < array.length; i++)
        {
            System.out.println(array[i]); 
        } 
    }
public int reverse(int[] array) {
    int left = 0;
    int right = array.length - 1;
    while( left < right ) 
    {  
        int temp = array[left];
        array[left] = array[right];
        array[right] = temp;
        left++;
    }
    return array.length;}
user3326162
  • 27
  • 1
  • 5
  • 3
    Please give us a short program that illustrates your problem. – Keppil Mar 26 '14 at 21:17
  • your question is bad... please give us some input – Pat B Mar 26 '14 at 21:18
  • You state, `"Here is my code, the for loop is what I am having problems with..."` -- which loop, and what problems are you having with it? Also, where do you call the method? You should consider making the method static so it can be called in the static main method without an instance. – Hovercraft Full Of Eels Mar 26 '14 at 21:31

2 Answers2

1

You don't need to return anything. The way Java handles arrays, when you use the method it changes the contents of the original array. Thus, you can just print it as is.

Epiglottal Axolotl
  • 1,048
  • 8
  • 17
0

For your specific code you need to:

  • Make your reverse method static, so it can be called from within the static main method without requiring that you first make an instance.

In other words, change the method signature to:

public static int reverse(int[] array) {
  • Then you need to call the method before iterating through the loop and printing out the results.

e.g.,

public static void main(String[] args) {
    int array[] = new int [7];
    array[0] = 5 ;
    array[1] = 10;
    array[2] = 11;
    array[3] = 19;
    array[4] = 13;
    array[5] = 14;
    array[6] = 16;
    reverse(array); // *** add this
    for(int i = 0; i < array.length; i++) {
        System.out.println(array[i]); 
    } 
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373