温馨提示×

怎么用java代码实现分页功能

小亿
84
2023-12-29 20:43:25
栏目: 编程语言

以下是一个用Java代码实现分页功能的示例:

public class Pagination {
    private int currentPage;
    private int pageSize;
    private int totalRecords;

    public Pagination(int currentPage, int pageSize, int totalRecords) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.totalRecords = totalRecords;
    }

    public int getTotalPages() {
        return (int) Math.ceil((double) totalRecords / pageSize);
    }

    public int getStartIndex() {
        return (currentPage - 1) * pageSize;
    }

    public int getEndIndex() {
        return Math.min(currentPage * pageSize, totalRecords);
    }
}

在使用时,可以将总记录数、当前页数和每页显示的记录数传递给构造函数,然后使用getTotalPages方法获取总页数,使用getStartIndexgetEndIndex方法获取当前页显示的记录的起始索引和结束索引。

示例用法:

public class Main {
    public static void main(String[] args) {
        int currentPage = 2;
        int pageSize = 10;
        int totalRecords = 37;

        Pagination pagination = new Pagination(currentPage, pageSize, totalRecords);
        int totalPages = pagination.getTotalPages();
        int startIndex = pagination.getStartIndex();
        int endIndex = pagination.getEndIndex();

        System.out.println("总页数:" + totalPages);
        System.out.println("起始索引:" + startIndex);
        System.out.println("结束索引:" + endIndex);
    }
}

运行结果:

总页数:4
起始索引:10
结束索引:20

这个示例中,总记录数为37,每页显示10条记录,当前页为第2页。所以总页数为4,当前页的起始索引为10,结束索引为20。

0