-1
 public static void copyList(int[]list) {

   int [] copyList = new int[list.length]; //define new array
   for(int i = 0; i < list.length; i++){
   copylist[i] = list[i];
  }
 System.out.println("The copy is: " + Arrays.toString(copyList) );

}

Hello Everyone. Having trouble writing this method. Do you have any suggestions on how I can improve this code? Am I in the right direction?

Thanks! -Patrick

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Please add the relevant language tag to your question.. Thanks! – Oliver Charlesworth May 31 '14 at 14:43
  • Sorry! I'm using java. – Pr0jectPat May 31 '14 at 14:44
  • what is the problem? If your intention is to print the element inside the list, why not directly using `System.out.println(java.util.Arrays.toString(list))`? If you want to get the copied list for later usage, you should return `int[]` instead of `void` – Robin May 31 '14 at 14:46
  • I'm getting a compilation error saying that it can't find the variable "copyList" which is the array that I defined before the for loop so it will not run. – Pr0jectPat May 31 '14 at 14:48
  • Paste the exact and complete error message you get. Tell us which line it refers to. That said, I fail to understand the point of a method which copies the array, then prints it, then throws it away. You could print the original array directly. Also look at System.arraycopy, which does a copy for you. – JB Nizet May 31 '14 at 14:50
  • I think rossum is correct.. – Robin May 31 '14 at 14:50
  • 3
    Your variable has the same name as the method, which is not good practice and confusing. You might also usefully read the Javadoc on `System.arraycopy()`. – rossum May 31 '14 at 14:51
  • Thanks it's always a small detail that i miss and spend hours trying to debug my code haha. – Pr0jectPat May 31 '14 at 14:57

1 Answers1

2

In Java variable names are case-sensitive.

Rename the variable inside the loop to copyList (with a capital L) and it should work like a charm.

Seb
  • 1,721
  • 1
  • 17
  • 30