简单分页算法

大部分程序中都会需要分页算法,很明显,必须把分页算法独立出来,如果也业务逻辑夹杂在一起,修改起来,是一件痛苦的事情。其实分页算法的设计就像是解方程,输入几个变量,求出其他几个变量。下面给出一种简单的设计:输入总记录数,当前的页面,跳转页数;输出请求的索引。当然,你还可以在这个简单算法基础上修改,输出其他的一些信息。

package paging; public class Page { /** * 每页显示的记录数,也就是你的请求数 */ public static final int PAGESIZE = 20; /** * 总记录数 */ private int records; /** * 当前页,从1开始计数 */ private int now_page; /** * 总页数 */ public int pages; /** * 请求位置,就是你从第几条记录开始请求 */ public int request_index; /** * 是否成功构造Page对象 */ public boolean ok = true; public Page() { } /** *一般在第一次请求的时候使用,因为不知道总记录数 */ public Page(int now_page) { this(PAGESIZE, now_page, 0); } public Page(int now_page, int go_count) { this(PAGESIZE, now_page, go_count); } /** * * @param records * 总记录书 * @param now_page * 当前页面的索引 * @param go_count * 跳转几页(支持负数) */ public Page(int records, int now_page, int go_count) { if ((now_page - 1) * PAGESIZE >= records || now_page <= 0) { System.out.println("构造Page失败-1!"); ok = false; } if (now_page + go_count <= 0 || (now_page + go_count - 1) * PAGESIZE >= records) { System.out.println("构造Page失败-2!"); ok = false; } this.now_page = now_page; this.records = records; this.request_index = (this.now_page + go_count - 1) * PAGESIZE; if (this.records % PAGESIZE == 0) { this.pages = this.records / PAGESIZE; } else { this.pages = this.records / PAGESIZE + 1; } } @Override public String toString() { return "pages:" + pages + " " + "request_index:" + request_index; } }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值