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)
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With