I have an array that I need to split in different arrays. I have an array of Strings and need to split it in different pages (different arrays).
At 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 Strings
int numberOfPages = (int) Math.floor(size/10);
The user then select 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 get an exception when I try to print the values of the new array.
Is there anyway to split an array in 'pages', and display these 'pages' as requestes?
@Edit1 I get a Nullpointer Exception
The error probably occurs in this line:
Arrays.copyOfRange(array,(0+10*(pageSelected-1),10*10+(pageSelected-1)));
Where there is an error with the brackets (the method requires three arguments, but from the method's perspective, you only provide two: the last two are grouped by brackets). You can use:
Arrays.copyOfRange(array,10*(pageSelected-1),10*10+(pageSelected-1));
(removed 0+ since this has no use).
Furthermore you made a semantical error: 10*10+(pageSelected-1) should be replaced by: 10+10*(pageSelected-1
So the full line reads:
Arrays.copyOfRange(array,10*(pageSelected-1),10+10*(pageSelected-1));
Although a better guideline would be to use small steps:
int i = pageSelected-1;
int g = 10*i;
Arrays.copyOfRange(array,g,g+10);//do something with the result
And to do it perfect, you better use variables for constants such that - if you change your mind - you can easily modify the number of items per 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 small remark: as @j_v_wow_d says, you should ceil the division, otherwise you will generate one page for 11 items. The correct code for numberOfPages is thus:
int numberOfPages = (int) Math.ceil((double) size/perpage);
If the pageSelected is indexed so that 0 is the 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"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With