Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

chris salvi
chris salvi
7,584 Points

question on JAVA example (more of a general question on coding with nested while loops)

I understand this site doesn't have lessons on Java, but my question really pertains more to how to understand these nested while loops below. This is from straight from a textbook, so I know the code is correct, but I don't understand the placement of the increment values of the var i and j. From what I gather, the code takes two strings of arbitrary length, lets call s1=food, s2=brood, and then starts checking the values.

Am I thinking of this correctly? If so, then why does the j++ increment stay outside the nested loop? I think the program is locking into place the first character of s1 while s2 cycles through all of its characters to see if there is a potential match, but then if there is no match, the j++ goes to the 2nd character in s2. Yet I don't see why the j++ should be outside the nested loop in this case.

boolean nothingInCommon;
nothingInCommon=true;

int i,j;

 i=0;

bigloop:while (i<s1.length()){

      j=0;
      while(j<s2.length()){
              if(s1.charAt(i)==s2.charAt(j))
                 nothingInCommon=false;
                 break bigloop;  
                 }
             j++;
}
     i++;
}

2 Answers

chris salvi
chris salvi
7,584 Points

also how does the j variable know to reset at the beginning of s2 once it has cycles through the initial character set and then the i++ is implemented?

If you matched your indentation level, i++ is indeed within the bigloop :) That's why proper indentation is so valuable.

boolean nothingInCommon;
nothingInCommon=true;

int i,j;

 i=0;

bigloop:while (i<s1.length()){

         j=0;
         while(j<s2.length()){     // <-- Beginning of inner loop
                  if(s1.charAt(i)==s2.charAt(j)) {
                           nothingInCommon=false;
                           break bigloop;  
                  }
                   j++;                            // Increment inner loop counter
         }                        // <-- End of inner loop

         i++;                                     // Increment bigloop counter
}          // <-- End of big loop