i have recrusive function which works fine. The problem is it gives stackoverflow error when the number of lines are huge. I want to put it in iterative, probably using a for loop. Need some help in doing it.
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
int nextLine = 0;
if (curLine == lines.length || errorSet.size() != 0) {
return errorSet;
} else {
String line = lines[curLine];
//validation starts. After validation, line is incremented as per the requirements
increment = 1 //As per requirement. Depends on validation results of the line
if (increment > 0) {
try{
Thread.currentThread().sleep(100);
}catch(Exception ex){
System.out.println(ex);
}
nextLine = (curLine + increment);
validate(nextLine, errorSet);
}
}
return errorSet;
}
Poster's description of the method:
The method does validates textlines, these lines has instructions of how much line has to be skipped, if the line is valid. So, if the line is valid that many of lines will be skipped using the increment. if the line is not valid increment will be 0.
I'm not sure why this was ever recursive in the first place. This is perfectly suited for the use of a FOR loop. use something like so:
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
if (errorSet.size() != 0)
return errorSet;
for (int curLine = 0; curLine < lines.Length; curLine += increment)
{
// put your processing logic in here
// set the proper increment here.
}
}
If the increment is always going to be 1, then you can just use curr++ instead of curLine += increment
for(String line : lines) {
// validate line here
if(!errorSet.isEmpty()) {
break;
}
}
The solution for your problem could be simple for loop or while, with logical expression for stop condition. Typically we use for loop when we have to pass through all elements of Iterable or array. In case when we are not aware how many loops we are going to do we use a while loop. Advantage of for loop over while, is that we for free have localized variables so we ca not use them out side of the loop, therefore we reduce possibility to have some bug.
You problem is that you have to break the program on two conditions:
When errorSet is not empty.
When the array of lines have no longer items.
As contradiction, we can say that your program should continue:
Until errorSet is empty,
and until line number is smaller than array size where they are stored.
This provide us to simply expression
errorSet.isEmpty()
lineNumber < lines.length()
We can combine them using logical operator && and use as a stop rule in for loop.
for(int lineNumber= 0; errorSet.isEmpty() && lineNumber< lines.length(); lineNumber++) {
//code to operate
}
Note:
Typically for logical expression is used operator &&, that assure that every part of the logical expression is evaluated. An alternative for this is &, that in case of false do not operate longer and return false. We could be tempted to use this operator for this expression but i would be bad idea. Because when we would traversed all lines without error code will generate IndexOutOfBoundException, if we switch the places then we would not have any optimization as first expression would be evaluated same number of times.
Related
This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?
e.g.
int count = 0;
do {
System.out.println("Welcome to Java");
count++;
} while (count < 10);`
It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).
For something simple like my above example, I would imagine that:
int count = 0;
while(count < 10) {
System.out.println("Welcome to Java"); count++;
}
would be generally considered to have been written in a better writing style.
Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?
(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)
If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.
do
{
// read data
} while ( /* data is not escape sequence */ );
The while statement continually executes a block of statements while a particular condition is true
while (expression) {
statement(s)
}
do-while evaluates its expression at the bottom of the loop, and therefore, the statements within the do block are always executed at least once.
do {
statement(s)
} while (expression);
Now will talk about functional difference,
while-loops consist of a conditional branch instructions such as if_icmpge or if_icmplt and a goto statement. The conditional instruction branches the execution to the instruction immediately after the loop and therefore terminates the loop if the condition is not met. The final instruction in the loop is a goto that branches the byte code back to the beginning of the loop ensuring the byte code keeps looping until the conditional branch is met.
A Do-while-loops are also very similar to for-loops and while-loops except that they do not require the goto instruction as the conditional branch is the last instruction and is be used to loop back to the beginning
A do-while loop always runs the loop body at least once - it skips the initial condition check. Since it skips first check, one branch will be less and one less condition to be evaluated.
By using do-while you may gain performance if the expression/condition is complex, since it is ensured to loop atleast once. In that casedo-while could call for performance gain
Very Impressive findings here,
http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html#while_loop
The do-while loop is basically an inverted version of the while-loop.
It executes the loop statements unconditionally the first time.
It then evaluates the conditional expression specified before executing the statements again.
int sum = 0;
int i = 0;
do
{
sum += ids[i];
i++;
} while (i < 4);
Reference material
Simply, when you want to check condition before and then perform operation while is better option, and if you want to perform operation at least once and then check the condition do-while is better.
As per your question a working example,
1. when I needed to find the field which could be declared in the same class or the super class or the super class of that super class and so on i.e. finding the field located in deep class hierarchy. (A extends B B extends C and so on)
public Field SearchFieldInHierarchy(Object classObj, String fieldName )
{
Field type = null;
Class clz = classObj.getClass();
do
{
try
{
type = clz.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e)
{
clz = clz.getSuperclass();
}
} while(clz != null || clz != Object.class);
return type;
}
2. When reading input stream from Http response
do
{
bytesRead = inputStream.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
totalBytesRead += bytesRead;
} while (totalBytesRead < buffer.length && bytesRead != 0);
You kind of answer the question yourself-when it needs to run at least once, and it makes sense to read it that way.
do - while loop allows you to ensure that the piece of code is executed at least once before it goes into the iteration.
In a while loop, the condition is tested before it executes code in the loop. In a do while loop, the code is executed before the condition is tested, resulting in the code always being executed at least once. Example:
$value = 5;
while($value > 10){
echo "Value is greater than 10";
}
The above would never output anything. If we do the same again like this:
$value = 5;
do{
echo "Value is greater than 10";
}while($value > 10)
It would output Value is greater than 10 because the condition is tested after the loop is executed. After this it would not output anything further.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.
For example do check this link: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
If the looping condition can only be known after a first step of the loop (when you do not want a condition before you enter the loop).
Typically:
do {
expr = ...;
while (expr);
Use the while Statement when you have to check a condition repeatedly and only when the condition is satisfied execute the loop
while(condition) //eg. a>5
{
Body of Loop
}
If you see the flow of control here you can see that the condition is checked before the execution of the loop, if the condition is not met the loop will not execute at all
In the Do-While statement the program will execute the body of the loop once and then it will check if the statement is true or not
do
{
Body of Loop
}
while(condition); //eg. a>5
If you notice the flow of control here you will see that the body is executed once, then the condition is checked. If the condition is False the Program will break out of the loop, if True it will continue executing till the condition is not satisfied
It is to be noted that while and do-while give the same output only the flow of control is different
/*
while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks
*/
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
It is very simple to distinguish between the two. Let's take While loop first.
The syntax of while loop is as follows:
// expression value is available, and its value "matter".
// if true, while block will never be executed.
while(expression) {
// When inside while block, statements are executed, and
// expression is again evaluated to check the condition.
// If the condition is true, the while block is again iterated
// else it exists the while block.
}
Now, let's take the do-while loop.
The syntax of do-while is different:
// expression value is available but "doesn't matter" before this loop, & the
// control starts executing the while block.
do {
// statements are executed, and the
// statements is evaluated and to check the condition. If true
// the while block is iterated, else it exits.
} while(expression);
A sample program is given below to make this concept clear:
public class WhileAndDoWhile {
public static void main(String args[]) {
int i = 10;
System.out.println("While");
while (i >= 1) {
System.out.println(i);
i--;
}
// Here i is already 0, not >= 1.
System.out.println("do-while");
do {
System.out.println(i);
i--;
} while (i >= 1);
}
}
Compile and run this program, and the difference becomes apparent.
Is there ever a situation where you must use a do while loop? Is it an accepted practice? It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
int i = 3;
while ( i > 0 ) { // runs 3 times
i--;
}
vs
int j = 3;
do {
j --;
} while ( j > 0 ); // runs 3 times
The same?
EDIT: I have seen the java doc, but
the example in the java docs doesn't look like it requires that the particular routine inside of the do while loop must be run in the do while loop instead of inside of a regular while loop!
Is there ever a situation where you must use a do while loop?
No: every do-while loop can be written as a while-loop by running the body once before the loop begins. However, there are certainly cases where it makes more sense to use the do-while construct (i.e. if you always want the loop to iterate at least once), which is why it exists in the first place.
Is it an accepted practice?
If you use it appropriately, then yes absolutely.
It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
That's right. You can read more about do-while in its tutorial.
This example maybe help you be clearer:
int i = 3;
System.out.print("while: ");
while (--i > 0){
System.out.print("x");
}
System.out.print("\ndo-while: ");
int j = 3;
do
{
System.out.print("x");
}while (--j > 0);
This prints
while: xx
do-while: xxx
A real time example.
There is a contest with 5 level.
In each level if you score 100 you can proceed to next level.
Less code for do while, but not for while.
boolean playContest()
{//do while
int level = 1;
int score;
do
{
score = 0;
score = play();
}while(score>99 && level++<6)
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
boolean playContest()
{//while
int level = 1;
int score;
while(level <6)
{
score = 0;
score = play();
if(score < 100)
break;
level++;
}
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
basic difference between while and do-while is do while will be executed at least once.
when do-while is best option?
in case when you want to execute some actions till you meet condition, of course you could achieve same thing by using while but early termination of loop with break, is nasty and ugly solution
When you want to execute the statement inside do for at least once, then you can go for it.
Directly from Docs
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once,
do {
statement(s)
} while (expression);
No, there is no time a do-while loops is the only option, it is used for convenience when you do not want to repeat code.
I want to know whether there is a performance difference in following two code blocks
1>
if(name == null) {
//something
}
if(name != null) {
//something
}
and
2>
if(name == null) {
//something
}
else {
//something
}
The first compares twice, the second compares once. The difference will not be noticeable, but it's there.
after benchmarkint it on 100.000.000 iterations, the first execution costs 719ms and the second 703ms.
I used a modulo so the conditions has to change every turn and avoid precompiled result. Please find the code below. I have noticed that this gap reduces when number of iterations increases.
public static void main(String[] args) {
Date start1 = new Date();
for(int i=0; i<100000000; i++) {
int it = i%2;
if(it == 0) {
double j = Math.random();
j++;
}
if(it != 0) {
double j = Math.random();
j++;
}
}
Date end1 = new Date();
Date start2 = new Date();
for(int i=0; i<10000000; i++) {
int it = i%2;
if(it == 0) {
double j = Math.random();
j++;
} else {
double j = Math.random();
j++;
}
}
Date end2 = new Date();
System.out.println((end1.getTime()-start1.getTime())+" / "+(end2.getTime()-start2.getTime()));
}
Just a brief comment to say that the compiler cannot optimize it in all cases, because name is visible within the first if block therefore it could have been modified in it, so it has to be checked again in the second if condition. Imagine this case:
if (name == null) {
// Does something
name = "Did it.";
}
if (name != null) {
// Does something else
}
It's clearly not equivalent to
if (name == null) {
// Does something
name = "Did it.";
} else {
// Does something else
}
If what you actually mean is that you should do something in one case and something else otherwise, please use if { ... } else { ... } - not just for (minimal) performance improvement, but also because your code should reflect what you actually mean.
Note that the two fragments are not necessarily equivalent, because the first block could re-assign name so that the second condition will also be true.
This can introduce hard to spot bugs, so I suggest that (before thinking about performance), you think about making the variable final if possible and use if/else when it makes sense (i.e. it should enter only one of the two branches) and chained if's when that makes sense (for example when the first if can establish a default value for the next one to use).
Yes there will, on the second one only one condition will be checked and on the first one two conditions would have to be checked.
An if clause that fails its evaluation has to make an "instruction jump" even if there is no else statement follwing it.
Assuming the first if is false, you'd be comparing these 2 execution scenarios:
1>
Check 1st condition
Skip to check 2nd condition
Do "something" inside the 2nd condition
2>
Check condition
Skip to "something" inside the else
Yes becuase both if cases will be evaluated in the first whereas only one if will be evaluated in the second.
yes, there will be a difference: in the second example, tehre's only 1 statement to be proofed, in the first one there are two.
but: the difference in performance will be absolutely minimal, in 99% of the cases you won't even notive any difference - make sure your code is as readable as it can be, thats much more important ;)
yes obviously the second code will perform inconsiderably better, because there is only one condition to check
I believe the compiler is smart enough to notice that the second if in the first example is redundant, so there won't be any performance change
I've heard that using while(true) is a bad programming practice.
So, I've written the following code to get some numbers from a user (with default values). However, if the user happens to type in -1, then it will quit the program for them.
How should this be written then without a while(true)? I can think of a condition to make the while loop go off that will get caught right away without continuing on until the next iteration?
Here is how I have it now:
public static void main(String[] args)
{
System.out.println("QuickSelect!");
while (true)
{
System.out.println("Enter \"-1\" to quit.");
int arraySize = 10;
System.out.print("Enter the size of the array (10): ");
String line = input.nextLine();
if (line.matches("\\d+"))
{
arraySize = Integer.valueOf(line);
}
if (arraySize == -1) break;
int k = 1;
System.out.print("Enter the kth smallest element you desire (1): ");
line = input.nextLine();
if (line.matches("\\d+"))
{
k = Integer.valueOf(k);
}
if (k == -1) break;
List<Integer> randomData = generateRandomData(arraySize, 1, 100);
quickSelect(randomData, k);
}
}
while (true) is fine. Keep it.
If you had a more natural termination condition, I'd say to use it, but in this case, as the other answers prove, getting rid of while (true) makes the code harder to understand.
There is a Single Entry Single Exit (SESE) school of thought that suggests that you should not use break, continue or abuse exceptions to do the same for some value of abuse). I believe the idea here is not that you should use some auxiliary flag variable, but to clearly state the postcondition of the loop. This makes it tractable to formerly reason about the loop. Obviously use the stands-to-reason form of reasoning, so it is unpopular with the unwashed masses (such as myself).
public static void main(String[] args) {
...
do {
...
if (arraySize == -1) {
...
if (k != -1) {
...
}
}
} while (arraySze == -1 || k == -1);
...
}
Real code would be more complex and you would naturally(!) separate out the inputing, outputting and core "business" logic, which would make it easier to see what is going on.
bool exit = false;
while (!exit) {
...
...
if (k == -1) {
exit = true;
}
else {
List <Integer> ....;
quickselect(.......);
}
}
But as has been said before, your while loop is a valid usage in this situation. The other options would simply build upon the if statements to check for the boolean and exit.
While having a loop like this is not technically wrong, some people will argue that it is not as readable as the following:
bool complete = false;
while (!complete)
{
if (arraySize == -1)
{
complete = true;
break;
}
}
Additionally, it is sometimes a good idea to have a safety loop counter that checks to make sure the loop has not gone through, say, 100 million iterations, or some number much larger than you would expect for the loop body. This is a secure way of making sure bugs don't cause your program to 'hang'. Instead, you can give the user a friendly "We're sorry but you've discovered a bug.. program will now quit.." where you set 'complete' to true and you end the program or do additional error handling. I've seen this in production code, and may or may not be something you would use.
while ( true ) is perfectly fine here, since the condition is really "while the user doesn't want to quit"!
Alternatively you could prompt for both the inputs on one line to simplify the logic, and use "q" for quit: this allows you to refactor the loop to "while ( !line.equals("q") )".
The problem is that you're doing an awful lot in that loop, rather than separating the functionality into simple methods.
If you want to stick to a procedural approach, you could move the reading of the array size and k into separate methods, and use the fact that the result of an assignment is the assigned value:
for (int arraySize; ( arraySize = readArraySize ( input ) ) != -1;) {
final int k = readKthSmallestElement ( input );
List<Integer> randomData = generateRandomData(arraySize, 1, 100);
quickSelect(randomData, k);
}
However that's still a bit ugly, and not well encapsulated. So instead of having the two != -1 tests on separate variables, encapsulate arraySize, k and randomData in an object, and create a method which reads the data from the input, and returns either a QuickSelect object or null if the user quits:
for ( QuickSelect select; ( select = readQuickSelect ( input ) ) != null; ) {
select.generateRandomData();
select.quickSelect();
}
You might even want to go to the next stage of creating a sequence of QuickSelect objects from the input, each of which encapsulate the data for one iteration:
for ( QuickSelect select : new QuickSelectReader ( input ) ) {
select.generateRandomData();
select.quickSelect();
}
where QuickSelectReader implements Iterable and the iterator has the logic to create a QuickSelect object which encapsulates arraySize, k, the list and the quick select operation. But that ends up being quite a lot more code than the procedural variants.
I'd only do that if I wanted to reuse it somewhere else; it's not worth the effort just to make main() pretty.
Also note that "-1" doesn't match the regex "\\d+", so you really do have an infinite loop.
If you really don't like while(true) you can always go for for(;;). I prefer the latter because it seems less redundant.
I saw this keyword for the first time and I was wondering if someone could explain to me what it does.
What is the continue keyword?
How does it work?
When is it used?
continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:
break terminates the loop (jumps to the code below it).
continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.
while (getNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}
With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.
Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.
for (count = 0; foo.moreData(); count++)
continue;
The same statement without a label also exists in C and C++. The equivalent in Perl is next.
This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.
aLoopName: for (;;) {
// ...
while (someCondition)
// ...
if (otherCondition)
continue aLoopName;
Let's see an example:
int sum = 0;
for(int i = 1; i <= 100 ; i++){
if(i % 2 == 0)
continue;
sum += i;
}
This would get the sum of only odd numbers from 1 to 100.
If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:
for(int i=0; i < 10; ++i) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This will print out only the odd numbers.
Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.
As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.
These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.
IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.
continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.
"continue" in Java means go to end of the current loop,
means: if the compiler sees continue in a loop it will go to the next iteration
Example: This is a code to print the odd numbers from 1 to 10
the compiler will ignore the print code whenever it sees continue moving into the next iteration
for (int i = 0; i < 10; i++) {
if (i%2 == 0) continue;
System.out.println(i+"");
}
As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).
It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.
This is why a lot of people fail to correctly answer what the following code will generate.
Random r = new Random();
Set<Integer> aSet= new HashSet<Integer>();
int anInt;
do {
anInt = r.nextInt(10);
if (anInt % 2 == 0)
continue;
System.out.println(anInt);
} while (aSet.add(anInt));
System.out.println(aSet);
*If your answer is that aSet will contain odd numbers only 100%... you are wrong!
Continue is a keyword in Java & it is used to skip the current iteration.
Suppose you want to print all odd numbers from 1 to 100
public class Main {
public static void main(String args[]) {
//Program to print all odd numbers from 1 to 100
for(int i=1 ; i<=100 ; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.
Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.
Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop.
Consider the following Program. '
public class ContinueBreak {
public static void main(String[] args) {
String[] table={"aa","bb","cc","dd"};
for(String ss:table){
if("bb".equals(ss)){
continue;
}
System.out.println(ss);
if("cc".equals(ss)){
break;
}
}
System.out.println("Out of the loop.");
}
}
It will print: aa cc Out of the loop.
If you use break in place of continue(After if.), it will just print aa and out of the loop.
If the condition "bb" equals ss is satisfied:
For Continue: It goes to next iteration i.e. "cc".equals(ss).
For Break: It comes out of the loop and prints "Out of the loop. "
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.
It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
for example
class Example{
public static void main(String args[]){
System.out.println("Start");
for(int i=0; i<10; i++){
if(i==5){continue;}
System.out.println("i : "+i);
}
System.out.println("End.");
}
}
output:
Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.
[number 5 is skip]
I'm a bit late to the party, but...
It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:
while ((buffer[i++] = readChar()) >= 0)
continue;
In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.
It's a little more obvious than the equivalent:
while (...)
{ }
and definitely better (and safer) coding style than using an empty statement like:
while (...)
;
continue must be inside a loop Otherwise it showsThe error below:
Continue outside the loop