分页页码计算算法
最近做网站用到了分页页码计算的算法,觉得之前一直用的不好,自己写了一个,拿出来与大家共享一下:
View Code
1 package cnblogs.xiaoqiu.test; 2 3 /** 4 * 1.如果是5个可见页码,1-12345,2-12345,3-12345,4-23456,5-34567,6-45678,7-56789 5 * 8-678910,9-678910,10-678910 6 * @author CHICHAO 7 * @date 2012-5-10 8 */ 9 public class WebTool { 10 public static PageIndex getPageIndex(int viewedIndex,int currentPage,int totalPage){ 11 int firstIndex = (currentPage<=viewedIndex/2+1?1:(currentPage-viewedIndex/2)); 12 int lastIndex = (firstIndex+viewedIndex-1>=totalPage?totalPage:firstIndex+viewedIndex-1); 13 if(lastIndex>=totalPage) 14 firstIndex = lastIndex - viewedIndex+1; 15 PageIndex pageIndex = new PageIndex(firstIndex,lastIndex); 16 return pageIndex; 17 } 18 public static void main(String[] args){ 19 System.out.println(getPageIndex(10, 119, 120).getFirstIndex()+"-"+getPageIndex(10,119,120).getLastIndex()); 20 } 21 } 22 23 class PageIndex{ 24 private int firstIndex; 25 private int lastIndex; 26 27 public PageIndex(int firstIndex, int lastIndex) { 28 this.firstIndex = firstIndex; 29 this.lastIndex = lastIndex; 30 } 31 public int getFirstIndex() { 32 return firstIndex; 33 } 34 public void setFirstIndex(int firstIndex) { 35 this.firstIndex = firstIndex; 36 } 37 public int getLastIndex() { 38 return lastIndex; 39 } 40 public void setLastIndex(int lastIndex) { 41 this.lastIndex = lastIndex; 42 } 43 }