7

I'm relatively new to java, and the passing by reference without pointers confuses me a little. I wrote a function for homework that requires me to return the length of user input, and assign use input to an array that is passed in, when the method exits the user input array is lost, what is wrong.

public static int readArray(char[] intoArray)
    {
        char[] capture = captureInputAsCharArray(); //User input comes back as char[]
        System.arraycopy(intoArray,0, capture, 0, capture.length);

        return capture.length;
    }

public static main(String[] args)
{
        size = readArray(arrItem7);  // item 7
        System.out.println(size);
        printOneInLine(arrItem7);  // prints individual elements of array
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
awiebe
  • 3,758
  • 4
  • 22
  • 33

3 Answers3

9

Because you have the arguments to System.arraycopy() backwards.

http://download.oracle.com/javase/6/docs/api/java/lang/System.html

public static void arraycopy(Object src,
                             int srcPos,
                             Object dest,
                             int destPos,
                             int length)

Swap intoArray and capture:

System.arraycopy(capture,0, intoArray, 0, capture.length);
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
0

To do what you want to do (get the user input and return its size), you can do this:

import java.util.*;


class Main{
  public static void main(String argv[])
  {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter something");
    String line = sc.nextLine();
    char [] my_array = line.toCharArray();
    System.out.println("You entered an input of length "+line.length());
  }

}

And it will give this:

$ java Main 
Enter something
Hello
You entered an input of length 5
lc2817
  • 3,722
  • 16
  • 40
-1

The reference itself is passed by value. In this case, you should return the very array (capture ) itself instead of length.

Santosh
  • 17,667
  • 4
  • 54
  • 79