1.

Solve : Java arraycopy method and 2D Arrays?

Answer»

In the programming language Java -

Basically, I am have been trying to use the System.arraycopy method to copy the elements of one array to another, and using a for loop to print out the elements, but I cannot get it to successfully copy the elements of one array to another.

The problem stems I think from my use of two dimensional arrays, because in the parameters for System.arraycopy the source position and destination position can only specify a single value, whereas I am using 2D arrays, which will hold two VALUES.

What can I do?

Here is a little IDEA of the array I have used
Code: [Select] LibraryItem[][] stItems = new LibraryItem[30][30];

//make items for the library
//For books prices £10 - £20
stItems[0][0] = new shortterm.Book(staff.getID(), "Java Now!", "Kris Jamsa", "J amsa Press", 1996,
"1-884-13330-4", 16.95);

stItems[0][1] = new shortterm.Book(staff.getID(), "Java in a Nutshell: A Desktop Quick Reference for Java Programmers",
"David Flanagan", "O'Reilly & Associates INC.", 1996,
"1-565-92183-6", 19.95);

And the arrayCopy method with the code for printing out the object attributes

Code: [Select] System.arraycopy(stItems, 3, refItems, 6, 10);

System.out.println('\N' +
"Price" + " " + " Book Title" +
"\n-----------------------------------------------------------" +
"-------------------------------------------------------------" +
"-----------------------");

for(int i = 0; i < refItems.length; i++){
for(int n = 0; n < refItems.length; n++){
if(refItems[i][n] instanceof reference.Book){
System.out.println("£" + ((reference.Book)refItems[i][n]).getPrice() + " " + refItems[i][n].getTitle() + " by " + ((reference.Book)refItems[i][n]).getAuthor() + ", " +
((reference.Book)refItems[i][n]).getPublisher() + ", " + ((reference.Book)refItems[i][n]).getYearPublished()
+ ", " + ((reference.Book)refItems[i][n]).getISBN() + ".");
}
}

}



Discussion

No Comment Found