Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go to next iteration

Here is what I want to do: In the loop, if the program finds an error, it will print out "Nothing" and go to the next loop (skips print out ""Service discovered at port: " + px + "\n"

   for(int px=PORT1; px <=PORT2; px++) { //search
       try{

           Socket s = new Socket(IPaddress,px);
       } catch(Exception e) {
               System.out.print("Nothing\n");
               // I want to go to next iteration

           }
       System.out.print("Service discovered at port: " + px + "\n");
   }

What code should I put in the catch? "break" or "next" or ??? (This is java)

like image 911
John Avatar asked Feb 08 '11 23:02

John


People also ask

How to move to the next iteration if a certain statement is true?

The following syntax illustrates how to move to the next iteration in case a certain if-statement is TRUE. Let’s first create a basic for-loop in R: for( i in 1:10) { # Regular for-loop cat ( paste ("Iteration", i, "was finished. ")) } # Iteration 1 was finished. # Iteration 2 was finished. # Iteration 3 was finished. # Iteration 4 was finished.

Is it possible to run a while loop over an iterable?

This is essentially what ron suggested, and you can easily run a while loop over an iterable like a for loop using an explicit iterator. It is in the case you dont have code after the inner loop. In the other case, it isnt. But that could work for me now if I modify something plus in your example you dont need the ok flag anymore.

How to go back to the outer loop from a for loop?

I don't think there is any other way to go back to the outer loop from a for loop. The only way that comes to mind is to use a while loop where the looping condition checks for there truth of a flag. This is essentially what ron suggested, and you can easily run a while loop over an iterable like a for loop using an explicit iterator.

Is there a way to continue a try-catch loop?

Alternatively, you can have a continue statement from inside the catch: This causes all of the code after the try/catch not to execute if an exception is thrown, since the loop is explicitly told to go to the next iteration. +1 for answering the original question and providing a good alternative. The keyword you're looking for is continue.


1 Answers

Use the continue keyword:

continue;

It'll break the current iteration and continue from the top of the loop.

Here's some further reading:

continue Keyword in Java

like image 112
Michael Avatar answered Sep 30 '22 15:09

Michael