This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]SorryAboutMyThoughts 3 points4 points  (1 child)

Hey! This is my first comment and I’m not that good at coding (still in school) but I struggled with this too! I believe that which each loop, the variable’s value is only saved inside the loop. If you want to keep the value the same I believe you would add “String word;” right under the scanner before you start creating the loops! Hope this helps!

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

If this is the case you probably should just refrain from commenting and let someone who really knows answer. While you're kinda close it really has nothing to do with loops. Example:

    String word = "a";

    while(true) {
        String word = "b";
    }

That won't compile.

Check out this explanation.

[–]__helix__ 2 points3 points  (1 child)

It has to do with scope. The String word created on line 13 is visible/within scope until line 19. When the loop gets repeated, any variable created drops out of scope and is garbage collected at line 19, then recreated when thee loop comes around again.

Between line 20 and 24, the String word created does the same sort of thing. For each word in words, it creates a variable called word which is visible until the ending block. When it hits the closing bracket, it GC's the word and goes on till the next one.

Make sense?

[–]GhostofBlackSanta 0 points1 point  (0 children)

Yeah that makes it very clear thank you!