Why do we need "continue" in this piece of code?
public class ContinueInForLoop {
public static void main(String[] args) {
String searchMe = "peter piper picked a peck of pickled peppers";
int noOfPs = 0;
int i;
for(i = 0; i<searchMe.length(); i++){
if(searchMe.charAt(i) != 'p')
continue;
noOfPs++;
}
System.out.println("There are " + noOfPs + " P's in " + searchMe);
}
}
Hi all, this an example taken form java official tutorials:
we can achieve the same output without "continue" key word, e.g
if(searchMe.charAt(i) == 'p')
noOfPs++;
Why bother putting "continue" keyword there?
Thanks for the help.
Tariq
Re: Why do we need "continue" in this piece of code?
Yes, programmers can not use correct, straight forward logic and make their program more complicated. Happens all the time.
Re: Why do we need "continue" in this piece of code?
Quote:
Originally Posted by
tariqm
this an example taken form java official tutorials
... from the section about the use of the continue keyword.
Branching Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)
Quote:
Why bother putting "continue" keyword there?
Wouldn't make much sense to avoid the use of the very keyword the tutorial explains there, would it?
db
Re: Why do we need "continue" in this piece of code?
Quote:
Originally Posted by
DarrylBurke
Thanks for the reply;
It may not make sense here in this specific example not to use continue keyword, but if we take in
the account that minimum code is easy to understand and debug, it makes perfect sense not to use
continue keyword.
What do you think..........
may be i am missing some important concept?????
Tariq
Re: Why do we need "continue" in this piece of code?
Quote:
Originally Posted by
tariqm
Thanks for the reply;
It may not make sense here in this specific example not to use continue keyword, but if we take in
the account that minimum code is easy to understand and debug, it makes perfect sense not to use
continue keyword.
What do you think..........
may be i am missing some important concept?????
Using a continue statement unconditionally is silly, because the code following that condition statement can not be reached anymore; if there is no code following the unconditional continue statement, the continue statement is useless; therefore, a continue statement is always used conditionally and there it doesn't do much more than avoid additional indentation cause by an else statement had the continue statement not been used. i.m.h.o. it's a bit too rigid to ban a continue statement; we could ban the while statement for the same (rigid) reason (while (<cond>) <statement> --> for( ;<cond>; ) <statement>)
A labeled continue statement has serious uses though ...
kind regards,
Jos