0

Is there anyone here who know how do this:

boolean condition = true;
for(int i=0; i<list.size() && condition; i++){
    if (***)
        condition = false;
}

with a for each loop, like that:

boolean condition = true;
for(String s : list && condition){
    if (***)
        condition = false;
}

I know the second loop will not work, but I would like to have the same behaviour without using the killing mortal ugly instruction "break".

spongebob
  • 8,370
  • 15
  • 50
  • 83
Teiki
  • 200
  • 2
  • 18
  • 3
    `break` is exactly what you should use here. It's a delightful instruction! You should become better friends with it. It's way more readable to me, even in the `for` case. – Claudiu Oct 27 '15 at 15:01
  • 1
    Nothing wrong with break. – dom farr Oct 27 '15 at 15:01
  • Where does `condition` depend on? A simple possibility would be to filter `list` so that each element has to be processed and the elements which have not to be processed are filtered out. – Smutje Oct 27 '15 at 15:01
  • Using break is a whole lot cleaner than putting the for loop in a try/catch block and throwing an exception when you wish to exit – phflack Oct 27 '15 at 15:14
  • @Smutje : Imagine a function to search for a specific ID in the object's list, when the ID is found the loop doesn't need to finish iterating. I had learn at school to not use break instruction, it's make code unclear. – Teiki Oct 28 '15 at 17:53

2 Answers2

3

Use break statement:

for(String s: list) {
   if (....) {
       break;
   }
}

BTW you can do it with any kind of loop and IMHO this is preferable because is more readable.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • OP doesn't want break statement. – Shivam Oct 27 '15 at 15:03
  • Oh, sorry. OP will have to understand that `break` is not ugly but one of the nice features introduced into C language ~45 (oh, my god) years ago. – AlexR Oct 27 '15 at 15:05
  • Haha thanks for the answer. I'm surprise to read that all of you, would use break. I don't like this instruction because it's not well readable and source of errors. GOTO is an old feature too and it's not a readable way to code. – Teiki Oct 28 '15 at 15:24
  • There is a serious difference between `goto` from one side and `break`+ `continue` from other. Goto can jump anywhere in your method including jumping to upper lines. Break and continue work for loops only. In fact break is usable in `switch` operator too. So, both break and continue are predictable: you do not have to look for the place where they jump. – AlexR Oct 29 '15 at 07:11
  • Yes true. break is more readable as goto. – Teiki Oct 29 '15 at 09:01
0

break is not ugly at all!!

boolean condition=true;
for ( String s : list ) {
    if ( !condition ) break;
    ...
    if () condition=false;
}
frifle
  • 810
  • 5
  • 24