Java – separate arrays in other arrays

I have an array. I need to divide it into different arrays I have a string array that needs to be divided into different pages (different arrays)

First, I get the length of the array

int size = array.length;

Then I got the number of pages I needed, knowing that each page should have only 10 strings

int numberOfPages = (int) Math.floor(size/10);

Then, the user selects the page he wants to view

int pageSelected = 2;

After that, I tried to split the array, with some exceptions I tried:

Arrays.copyOfRange(array,(0+10*(pageSelected-1),10*10+(pageSelected-1)));

An exception occurred when I tried to print the value of a new array

Anyway, split the array in "pages" and display these "pages" as requests?

@Edit1 I got a null pointer exception

Solution

The error may occur on this line:

Arrays.copyOfRange(array,10*10+(pageSelected-1)));

There is an error in parentheses (the method requires three parameters, but from the perspective of the method, you only provide two: the last two are grouped in parentheses) You can use:

Arrays.copyOfRange(array,10*(pageSelected-1),10*10+(pageSelected-1));

(delete 0 because it's useless)

In addition, you made a semantic error: 10 * 10 (pageselected-1) should be replaced by: 10 10 * (pageselected-1)

The whole bank is as follows:

Arrays.copyOfRange(array,10+10*(pageSelected-1));

Although a better guideline is to use small steps:

int i = pageSelected-1;
int g = 10*i;
Arrays.copyOfRange(array,g,g+10);//do something with the result

To do your best, you'd better use variables for constants, so - if you change your mind - you can easily change the number of items per page:

int i = pageSelected-1;
int perpage = 10;
int g = perpage*i;
Arrays.copyOfRange(array,g+perpage);//do something with the result

One last comment: just like @j_ v_ wow_ D said that you should refine the Department, otherwise you will generate a page for 11 projects Therefore, the correct code for numberofpages is:

int numberOfPages = (int) Math.ceil((double) size/perpage);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>