This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, I need to make a loop that iterates through a list of servers to connect to, and if it connects to one successful, breaks the loop. If a particular server rejects the connection, then an exception is thrown. How can I make it so that it skips the failed server and tries the next one? I didn't think I was doing anything wrong, but it still continues to try to connect to the same server, over and over again. Heres the basic idea of what I'm trying to do, but whenever I implement it into real code it doesn't work:
Try a boolean isConnected = false; before the loop, and at the end of the try isConnected = true; Then you can add !isConnected to the middle part of the for-loop heading.
Why are you only incrementing your counter in the catch? That may cause you to go into an infinite loop.
I suspect the problem is in some code you didn't show us. Why? See the code at the bottom of this post. When I make your code compilable and test the logic it runs as expected. So here is what you should do:
1) Tell us exactly how it doesn't work. Do you get an exception, does the program crash? What exactly is the behavior, and how does that contrast with what you expect to happen?
2) Show us the real code. Make a small, compilable, demonstration application that misbehaves the same way your real code does, and show us this sample (it is called making a SSCCE. Who knows, perhaps in the process of making the SSCCE you will find the error and fix it.
My example SSCCE based on your code.
Expect it to report failure 2 times, then succeed on the third.