溫馨提示×

怎么用java代碼實現分頁功能

小億
126
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女