以下是一個用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
方法獲取總頁數,使用getStartIndex
和getEndIndex
方法獲取當前頁顯示的記錄的起始索引和結束索引。
示例用法:
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。