问题描述
定义了两个list,listRkd得到数据库的值,拼接成字符串后放到了list.add里,进入循环的时候出现异常了,假如for循环现在要循环10次,我的list里的值现在只有8个值,那么我用showData.apend(list.get(i))循环取list的值到第八次就取完了,第九次执行show.append(",")就会报错,我怎么在show.append(",")外面做个判断,判断list.get(i)的值已经去完了,不用在进行字符串拼接了,或者进来让第九次和第十次执行空循环也行 String start = request.getParameter("start");String limit = request.getParameter("limit");Integer startInt = Integer.parseInt(start);Integer limitInt = Integer.parseInt(limit);RukudanDAO rkdDAO = new RukudanDAO();List<String> list = new ArrayList<String>();int rkCount = rkdDAO.RkCount();List<Rkd> listRkd = rkdDAO.GetRKInfo();Iterator<Rkd> iter = listRkd.iterator();while (iter.hasNext()) {Rkd rkd = iter.next();StringBuffer data = new StringBuffer();data.append("{wh:").append(rkd.getWh()).append(",rq:'").append(rkd.getRq() + "'").append(",bmmc:'").append(rkd.getBmmc() + "'").append(",gysmc:'").append(rkd.getGysmc() + "'").append(",ckmc:'").append(rkd.getCkmc() + "'").append(",slhj:'").append(rkd.getSlhj() + "'").append(",jehj:'").append(rkd.getJehj() + "'").append(",zy:'").append(rkd.getZy() + "'").append(",cg:'").append(rkd.getCg() + "'").append(",bg:'").append(rkd.getBg() + "'").append(",jz:'").append(rkd.getJz() + "'").append(",czy:'").append(rkd.getCzy() + "'").append("}");list.add(data.toString());System.out.print(data.toString()); }StringBuffer showData = new StringBuffer();int end = startInt+limitInt;for(int i=startInt;i<end;i++){showData.append(list.get(i));if(i!=end){showData.append(",");}}
解决方案
int end = startInt+limitInt; for(int i=startInt;i<end;i++){ showData.append(list.get(i)); if(i!=end){ showData.append(","); } } 中的end 值应该为list.size();改成如下,试试.int end = startInt+limitInt; for(int i=startInt;i<end;i++){ if(i>=list.size()){ break; } showData.append(list.get(i)); if(i!=end){ showData.append(","); } }
解决方案二:
看你的代码应该是ajax分页代码,如果单前页的end值超过list.size()就会出现index溢出的异常;你在循环之前对end值判断赋值就可以了:int end = startInt+limitInt;end = end > list.size() ? list.size() : end; for(int i=startInt;i<end;i++){ showData.append(list.get(i)); if(i != (end - 1)){ showData.append(","); } }