Splitting array in other arrays
I have an array that I need to split into different arrays. I have an array of strings and need to split it on different pages (different arrays).
First I get the length of the array using
int size = array.length;
And then I get the number of pages I need, knowing that each page should only have 10 lines
int numberOfPages = (int) Math.floor(size/10);
Then the user chooses which page he wants to see
int pageSelected = 2;
After that, I tried to split the array but got some exceptions. I tried:
Arrays.copyOfRange(array,(0+10*(pageSelected-1),10*10+(pageSelected-1)));
I am getting an exception when I try to print the values of a new array.
Do I need to split the array into "pages" and display those "pages" as requests?
@ Edit1 I am getting Nullpointer exception
source to share
Probably the error occurs on this line:
Arrays.copyOfRange(array,(0+10*(pageSelected-1),10*10+(pageSelected-1)));
If there is an error in parentheses (this method requires three arguments, but in terms of the method, you only provide two: the last two are grouped by parentheses). You can use:
Arrays.copyOfRange(array,10*(pageSelected-1),10*10+(pageSelected-1));
(removed 0+
as it doesn't make sense).
Also, you made a semantic mistake: 10*10+(pageSelected-1)
should be replaced with:10+10*(pageSelected-1
So the full line reads:
Arrays.copyOfRange(array,10*(pageSelected-1),10+10*(pageSelected-1));
Though the best guide would be using small steps:
int i = pageSelected-1;
int g = 10*i;
Arrays.copyOfRange(array,g,g+10);//do something with the result
And for that you are better off using variables for constants, so - if you change your mind - you can easily change the number of elements on the page:
int i = pageSelected-1;
int perpage = 10;
int g = perpage*i;
Arrays.copyOfRange(array,g,g+perpage);//do something with the result
Finally, a little note: as @j_v_wow_d says, you must ceil
division, otherwise you will create one page for the items 11
. So the correct code is for numberOfPages
:
int numberOfPages = (int) Math.ceil((double) size/perpage);
source to share
If pageSelected
indexed so that 0 is first:
String[] array = {"a", "b", "c", "d", "e", "f"};
int pageSize = 2;
int pageSelected = 2;
final String[] pageData =
Arrays.copyOfRange(
array,
(pageSelected * pageSize),
(pageSelected * pageSize) + pageSize);
The outcome of this is that pageData
contains ["e", "f"].
source to share
Arrays.copyOfRange(array,(0+10*(pageSelected-1),10*10+(pageSelected-1)));
I think you mean this :)
Arrays.copyOfRange(array,0+10*(pageSelected-1),10+10*(pageSelected-1));
Look at the position +
and *
after the second comma.
But it would be easier to read if it wasn't one-liner
int offset = 10 * (pageSelected - 1);
Arrays.copyOfRange(array, offset, offset + 10);
Or even better
public static final int PER_PAGE = 10;
/* (...) */
int offset = PER_PAGE * (pageSelected - 1);
Arrays.copyOfRange(array, offset, offset + PER_PAGE);
source to share