一:使用带有标记的break语句,break默认是结束当前的while/for/case语句,但是当要一次结束多层嵌套的时候可以通过添加标记的方法,具体操作如下:
@Test
public void query() {
OtaInfoVo otaInfoVo = new OtaInfoVo();
OtaDataVo otaDataVo = new OtaDataVo();
OtaMsgDetailVo otaMsgDetailVo =new OtaMsgDetailVo();
OtaInfoPageReq otaInfoPageReq = new OtaInfoPageReq();
otaInfoPageReq.setPageNum(1);
otaInfoPageReq.setPageSize(10);
ResultPageVO<OtaInfoVo> otaInfoVoResultPageVO = iotOtaInfoControl.queryOtaAppkeyPage(otaInfoPageReq);
PageInfo<OtaInfoVo> data = otaInfoVoResultPageVO.getData();
List<OtaInfoVo> list = data.getList();
//打标签
hh:
for (OtaInfoVo vo : list) {
OtaDataPageReq req = new OtaDataPageReq();
req.setOtaInfoId(vo.getId());
req.setPageNum(1);
req.setPageSize(10);
ResultPageVO<OtaDataVo> query = otaDataControl.query(req);
if (query.getData() != null && CollectionUtils.isNotEmpty(query.getData().getList())) {
otaInfoVo = vo;
List<OtaDataVo> list1 = query.getData().getList();
for (OtaDataVo vo2 : list1) {
if (vo2.getAppkey() !=null){
otaDataVo = vo2;
}else {
continue;
}
OtaMsgDetaiPageReq otaMsgDetaiPageReq = new OtaMsgDetaiPageReq();
otaMsgDetaiPageReq.setOtaDataId(vo2.getDataid());
otaMsgDetaiPageReq.setPageNum(1);
otaMsgDetaiPageReq.setPageSize(20);
ResultPageVO<OtaMsgDetailVo> query2 = otaDataControl.queryOtaMsgDetail(otaMsgDetaiPageReq);
if (query2.getData() != null && CollectionUtils.isNotEmpty(query2.getData().getList())) {
otaMsgDetailVo = query2.getData().getList().get(0);
break hh;
}
}
}
}
}
感觉上面实战看着比较费劲,看这个:
public static void main(String[] args) {
String a1 = "";
String b1 = "";
here:
for (int i = 1; i <= 4; i++) {
a1 = "外层循环第" + i + "层";
for (int j = 1; j <= 4; j++) {
b1 = "内层循环第" + j + "层";
if (2 == j & 2 == i) {
break here;//结束循环到here层,也就是直接结束两层循环
}
}
}
}
标签有两种用法,可以加break,也可以加continue,使用场景如下:
(1)带标签的continue不往下执行语句,直接返回标签所在处的循环开头,并继续执行该循环.
(2)带标签的break不往下执行语句,直接中断并退出标签所在处的循环.
二:使用一个变量来标记,这种方法容易想到,但是在遍历的过程中每次都需要判断,执行效率并不高,具体操作如下:使用state变量来决定是否结束循环体
public static void main(String[] args) {
String a2 = "";
String b2 = "";
Boolean state = true;
for (int i = 1; i <= 4 && state; i++) {
a2 = "外层循环第"+i+"层";
for (int j = 1; j <= 4 && state; j++) {
b2 = "内层循环第"+j+"层";
if (2 == j & 2 == i) {
state = false;
}
}
}
}
三:使用try/catch强制跳出循环,该方法也可使用,但是当循环体内部发生其他异常,也可能导致提前结束循环,具体操作如下:
public static void main(String[] args) {
String a3 = "";
String b3 = "";
try {
for (int i = 1; i <= 3; i++) {
a3 = "外层循环第" + i + "层";
for (int j = 1; j <= 3; j++) {
b3 = "内层循环第" + j + "层";
if (2 == j & 2 == i) {
throw new Exception();
}
}
}
} catch (Exception e) {
System.out.println(a3 + b3);
}
}
总的来说,在工作中更推荐第一种,灵活性更高。另外还可以使用return提前终止代码执行,前提是后边没有要执行的代码了。
创作不易,如果这篇文章对你有用,请点赞。有其他建议请在下方留言评论,谢谢♪(・ω・)ノ!