判断list取值完毕

定义了两个list,listRkd得到数据库的值,拼接成字符串后放到了list.add里,进入循环的时候出现异常了,假如for循环现在要循环10次,我的list里的值现在只有8个值,那么我用showData.apend(list.get(i))循环取list的值到第八次就取完了,第九次执行show.append(",")就会报错,我怎么在show.append(",")外面做个判断,判断list.get(i)的值已经去完了,不用在进行字符串拼接了,或者进来让第九次和第十次执行空循环也行
[code="java"]
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 list = new ArrayList();
int rkCount = rkdDAO.RkCount();
List listRkd = rkdDAO.GetRKInfo();
Iterator 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(",");
    }
}

[/code]

2个回答

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 if(i>=list.size()){
break;
}
showData.append(list.get(i));

if(i!=end){

showData.append(",");

}

}

看你的代码应该是ajax分页代码,如果单前页的end值超过list.size()就会出现index溢出的异常;你在循环之前对end值判断赋值就可以了:
[code="java"]
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(",");

}

}

[/code]

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问