-3

I need to reverse an array for example move what ever is in spot 5 to 0, 4 to1, 3 to 2.

            int size, length;

    System.out.print("how big of a list do you have: ");
    size=reader.nextInt();

    length=size-1;

    int [] array = new int [size];

    for (int count=0; count < array.length; count ++){
        System.out.println("enter a number: ");
        array [count] = reader.nextInt();
    }
    for (int count=length; count > 0; count --)
    array [(length-count)];
}

}

I am doing this in eclipse and I keep getting an error in the last line saying that I am not using an operator/expression : array [(length-count)]; but I dont know why the minus sign is not working? or if my program will work in general it did not get past the build part.

meda
  • 45,103
  • 14
  • 92
  • 122

2 Answers2

1

Array[(length-count)] doesn't work because it's a value, it's the same as writing

    0;

It is not a call to a procedure or an operation, so it is an error.

Try this:

    int temp = 0 ;
    for(int start=0, end = numbers.length -1 ; start < end; start++, end--){
        //swap numbers
        temp = array[start];
        array[start] = array[end];
        array[end] = temp;
    }
BackSlash
  • 21,927
  • 22
  • 96
  • 136
1
int temp = 0;
for (int i = 0; i < array.length / 2; i++)
{
    int temp = array[i];
    array[i] = array[array.length - i--];
    array[array.length - i--] = temp;
}

temp is used so that numbers don't overwrite each other. Think of it like getting food from a fridge. The milk is behind the water, and you want some milk. In order to get the milk, you take the water and put it in your hand (temp would be the hand). You then put the milk where the water was and the water where the milk was. Without the "hand", you would have lost your water (fallen on the floor, or in the case of temp, lost in memory) and only be left with milk.

syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • thanks this worked but if its not too much too ask can someone explain how this works and what specifically temp does. – user2016588 Jan 28 '13 at 00:53