突破Java中复杂的循环结构 [英] Breaking out of complex loop structure in Java

查看:165
本文介绍了突破Java中复杂的循环结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者.我具有以下循环结构:

Im a beginner in Java. I have the following loop structure:

loop1:
for(int j=0; j<a.size(); j++){

    if(a.get(j).equals(10)){
        System.out.println(a.get(j));
    } else {
        do {
            System.out.println(a.get(j));
        } while(a.get(j).equals(20)); 
        break loop1;
    }
}

这是我正在尝试做的基本结构.所以我想在else部分中的do while循环得到满足时跳出for循环(do- while循环执行一次,无论提到的条件如何,我都不想退出循环,但是我要在实际满足条件时退出循环).我怎么做?我尝试按代码所示进行破坏,但是在通过do-while循环进行第一次迭代后停止.我要去哪里错了?

This is a basic structure of what im trying to do. So I want to break out of the for loop when the do while loop in the else part is satisfied(the do- while loop executes once irrespective of condition mentioned, I dont want to exit the loop then, but I want to exit the loop when the condition is actually satisfied). How do I do that? I tried breaking as shown in code, but it stops after first iteration through do-while loop. Where am I going wrong?

我想打印ArrayList a中的值,从10到20 ...并且10可以在列表中的任何位置而不是开头.

I want to print the values in the ArrayList a starting from 10 until 20...and 10 can be anywhere in the list and not the beginning.

Eg. ArrayList a contains {1,2,3,4,5,6,7,8,9,10,11,12,13...20}
I want to print values in the ArrayList from values 10 to 20 (including 10 and 20). 

列表中没有重复的元素.因此,列表中只有一个10和一个20,并且始终按升序排列.

There are no duplicate elements in the list. So there is only one 10 and one 20 in the list and it is always in the increasing order.

推荐答案

int i=0;
boolean found10,found20;
found10=false;
found20=false;
while(i<a.size&&(!found20))
{
    if(a.get(i)==10)
        found10 = true;
    if(found10)
        System.out.println(a.get(i));
    if(a.get(i)==20)
        found20 = true;
    i++;
}

这篇关于突破Java中复杂的循环结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆