Friday, June 1, 2018

Java array is lost when exiting method




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
}

Answer



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);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...