user1166085 user1166085 - 5 months ago 9
Java Question

How to break out of a while loop in java?

// Setup dummy array
ArrayList<Integer> list = dateArray;
int counter = 1;
while (list.size() != 0) {
for (int j = 1; j < list.size(); j++)
{

//System.out.println(list.get(0) + " and " + list.get(j));
int difference = list.get(0) - list.get(j);
if (difference <6){
System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );
counter= counter +1;
System.out.println ("Counter is " + counter);
if (counter >= 4){
System.out.println ("j = " + j + " Counter =" + counter);
if (j ==list.size()-1) {
System.out.println ("here " + counter);
break;
}
}
}
}
list.remove(0);
};


Output:

1 and 2 and size is 4
Counter is 2
1 and 3 and size is 4
Counter is 3
1 and 4 and size is 4
Counter is 4
here 4
2 and 3 and size is 3
Counter is 5
3 and 4 and size is 2
Counter is 6
here 6


Ideally, i want it to stop when Counter is 4 and don't go on to execute "2 and 3 and size is 3 "

Much appreciated!

Answer

You need to use a label for the loop . Please try below snippet :

// Setup dummy array
    ArrayList<Integer> list = dateArray;
    int counter = 1;
outerwhileloop:
    while (list.size() != 0) {
        for (int j = 1; j < list.size(); j++)
        {

            //System.out.println(list.get(0) + " and " + list.get(j));
            int difference = list.get(0) - list.get(j);
            if (difference <6){
                System.out.println(list.get(0) + " and " + list.get(j) + " and size is " +list.size() );    
                counter= counter +1;
                System.out.println ("Counter is " + counter);
                if (counter >= 4){
                    System.out.println ("j = " + j + " Counter =" + counter);   
                    if (j ==list.size()-1) {
                        System.out.println ("here " + counter); 
                        break outerwhileloop;
                    }   
                }
            }
        }
        list.remove(0);
    };