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

Java

My while-loop doesn't want to exit. Perturbing!

I'm coding a little Zork inspired game to test my beginner skills that I have learned so far. I've added a while-loop, but it doesn't want to exit when the expression becomes false. I can't understand why. I've tried a few things, even adding a 'break;'. Nothing has worked so far.

I can't be that off, can I?

My code below:

String levelOneAction = console.readLine("Enter an action: ");

char ring = levelOneAction.charAt(0);

 ring = Character.toLowerCase(ring);

            while(ring != 'r')
            {
                System.out.println("...text...");
                levelOneAction = console.readLine("Try another action: ");          
            }
            System.out.println("...text...");

3 Answers

"ring" never changes inside the loop. You assign a new value to the String, but you also need to assign it to the char once again! To solve your problem, simply add

ring = levelOneAction.charAt(0);
ring = Character.toLowerCase(ring);

inside the loop.

EDIT: Fixed a mistake as pointed out by Gábor :)

Awesome! I had to leave out 'char' for 'char ring = levelOneAction.charAt(0)' as that was already defined before the while-loop. Then it worked. It's an interesting process, but I think I get it. Thanks again!

I don't think your ring variable is ever changed inside the loop. To exit the loop ring will need to equal 'r', or you'll need to mannually 'break' from the loop.

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Also...you are about to be eaten by a grue.