0

I have an array of type int:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

I want to take the value at the end, and bring it the beginning and shunt the rest of the elements to the right, so my output will look like: 5, 1, 2, 3, 4

I've considered using an ArrayList, but the assignment seems to want me to just use a primitive array.

Thanks

5
  • 1
    What did you try so far ? That's quite simple. Commented Oct 28, 2014 at 12:22
  • 1
    It would be easier with LinkedList Commented Oct 28, 2014 at 12:22
  • 1
    do temp = array [4], then move all the elements of the array up by one, like array [1] = array [0] then finally make array [0] = temp. Thats the algorithm Commented Oct 28, 2014 at 12:24
  • I tried using an ArrayList, but i don't think that's what they are looking for. It's homework for my java class yes. Well, a small part of a project on inversion. Commented Oct 28, 2014 at 12:25
  • 2
    @jgr208 Did what you suggested with a for loop. Many thanks! Commented Oct 28, 2014 at 12:42

3 Answers 3

1

Here the code, try this

public class arrayformat {

    public static void main(String[] s)
    {
                int[] array = {1,2,3,4,5};


                int temp = array[4];

                for(int i=array.length-1;i>0;i--)
                {
                    array[i]=array[i-1];
                }

                array[0]= temp;

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

    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You wont need an ArrayList or a LinkedList to achieve that. I'm not going to give you a full solution but try to think about what you know about arrays and what you want to achieve (which value should be placed where (try to work with the array's index)). If you dont have to do an inplace reversion it can be very helpful to create a second array to work with. Check out http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html for a introduction to java arrays.

Comments

0

You can try next:

    int arr[] = new int[]{1,2,3,4,5};
    int val = arr[arr.length-1];
    System.arraycopy(arr, 0, arr, 1, arr.length-1);
    arr[0] = val;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.