Using Array methods in a For loop

Hello everyone,
Right now I am working on a program that shifts elements in an array one position forward. I am doing it by making a copy of the input array, then using a for loop replacing each element of the copy (rotated[i+1]) with the 'previous' element from the input array(a[i]). But for some reason, even though to me it doesn't look like the input array is being edited at all, its values are changing each execution of the loop. I have added println's so I could help track the changes. Eventually, the input array (a) is full of the value that is in a[0].

Can anyone see where this is occuring? Thanks.

import java.io.*;
import java.util.*;
public class arrayRotater
{

public static void main(String[] args) {
int[] list = {3, 8, 19, 7};
rotateRight(list);
System.out.println(Arrays.toString(list)); // [7, 3, 8, 19]
}


public static int[] rotateRight (int[] a)
{
int[] rotated = a;
System.out.println("Starting for loop
");
for (int i = 0; i < a.length - 1; i++)
{
System.out.println("The first element is " + a[0] + " for cycle " + i);
System.out.println("The second element is " + a[1] + " for cycle " + i);
System.out.println("The third element is " + a[2] + " for cycle " + i);
System.out.println("The fourth element is " + a[3] + " for cycle " + i);
System.out.println("");
rotated[i+1] = a[i];
}
return rotated;
}
}

Comments

  • javamike,
    The fly in the ointment is the statement:
    [code]int[] rotated = a;[/code]
    What that does, because an array is an object, is make the array "rotated" [u][b]point[/b][/u] to array "a" (which also points to array "list").
    Therefore the statement
    [code]rotated[i+1] = a[i][/code]
    moves element i to element i + 1 in the [b][u]same[/u][/b] array.

    What will fix things up is to [b]change[/b] the declaration of array "rotated" so that it is a [u][b]new[/b][/u] array of int(s) with a length equal to the length of the array "a".
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion