Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 682
awiebe Avatar asked Nov 03 '11 04:11

awiebe


People also ask

How do you pull an array in Java?

get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned. index: The particular index of the given array.

How do you check if an element is the last element in an array Java?

Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

How do you remove an element from the end of an array in Java?

We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.


1 Answers

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);
like image 137
Brian Roach Avatar answered Sep 28 '22 07:09

Brian Roach