Snare_Dragon
Snare_Dragon

Reputation: 59

How do you use the replace command with an Array?

I am trying to take an int Array, and move all the integers to the right by one place, the last number in the array will go to array[0]. Like this:

public static void main(String[] OOOF)
{
    Scanner in = new Scanner(System.in);
    System.out.print("Enter the integer of how long you want the array to be: ");
    int length = in.nextInt();
    int[] array = new int[length];

This segment fills the array with integer values inputted by the user:

    for(int i = 0; i < length; i++)
    {
        System.out.println("Enter in an integer:");
        array[i] = in.nextInt();
    }
    System.out.println(array);

This next segment swaps the end int and the first int:

    int swap1 = array[0];
    array[0] = array[length];
    array[length] = swap1;
    System.out.println(array);

This is where I am having trouble, I want to use some type of command that replaces that int at a specific point and then removes the original to be stored. Next... repeat that process in the for a loop until it is complete. I know that it is possible but haven't taken a computer science class in a couple of years...

    int safe = myArr[length];
    for(int j = 0; j < length; j++)
    {
        myArr[j+1] = myArr[j];
    }
}

Please Help??

Upvotes: 1

Views: 60

Answers (1)

Syrius
Syrius

Reputation: 941

I'm not entirely sure if I understood it correctly. But this is the way that I would solve it (without the scanner, but your code there can easily be used):

System.out.println("Enter the integer of how long you want the array to be: ");
int length = 4;
int[] array =  {1,2,3,4};
int safe = array[array.length-1];
for(int j =array.length-1; j >0; j--)
{
  array[j] = array[j-1];
}
array[0] = safe;

They main difference is the last forloop. You want to push every integer one to the right, so it makes sense to fill it up from the right side by counting i down. Otherwise you copy the 0th element to the first position. Then you copy the 1st element to the 2nd position (the first element is the same that was at position 0). You're then basically just filling the array with the first element. In the end you plug the element that you safed before in at the first position. Hope this helps.

Upvotes: 1

Related Questions