Steven Branigan Steven Branigan - 1 year ago 70
Java Question

JAVA - Nested for loop not returning to outer loop

I am having an issue with a nested for-loop that I have written. Essentially I have a json file that I am trying to parse into individual variables so that I can then add those variables to a database for querying. I know I am probably going the wrong way about this but please bare with me...

This is the outer and inner loop:

for (int x = 0; x <= fixtures.length; x++) {
String testFixture = fixtures[x];
testFixture = testFixture.replace("\"", "");
testFixture = testFixture.replace("[", "");
testFixture = testFixture.replace("{", "");
testFixture = testFixture.replace("}", "");
String[] singleFixture = testFixture.split(",");

for (int i = 0; i <= singleFixture.length; i++) {
String test = singleFixture[i];
String[] fix1 = test.split(":");

The output of this is a json array at fixtures[0] and that's it...

fixtures.length = 381. So I would expect that when the inner loop finishes, it will return to the top of the outer loop and x would be incremented by +1.

What's happening is the inner loops finishes and that's it. x does not iterate to fixtures.length i.e. 381 times.

Each index in fixtures is a JSON array with 34 key pairs. So singleFixture.length = 34. That works, i iterates 34 times. Then the loop ends and the outer loop is ignored.

Does anyone have any ideas what I've done wrong here?

Really appreciate the help. Thanks.

Answer Source

The reason why your loop did not went to its next iteration is because the try-catch clause is catching the exception. See try-catch on the outer block of your main for-loop.

 //!!! The try is catching the exception for you. Remove it to see the real problem.
 try {
        URIBuilder builder = new URIBuilder("");
        for (int x = 0; x <= fixtures.length; x++) {
            // Exception somewhere
  catch(Exception e) {


If you comment out the try { ... } catch { ... } clause and add throws Exception to the main() method like;

public static void main(String[] args) throws Exception

Then the problem will become obvious. Follow the stack trace and you should be able to fix the core problem.

Also, as mentioned by others the loop logic you got there is wrong. It should be < less than not <= less than equals, the latter will definitely trigger the index out of bound exception.


From my observation, I think the nested loop must have triggered the index of out bound exception which caused the code to get into the catch path, resulting the loop to not iterate further.

I will recommend you to fix the loops first. E.g.
for (int x = 0; x < fixtures.length; x++) {

However if you are still having trouble and you would like us to have a look at the stack trace, please kindly post another question and we can investigate further.

Glad to help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download