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 Java Basics Perfecting the Prototype Looping until the value passes

Moussa Ismail
Moussa Ismail
4,175 Points

I've hit a wall, what am I doing wrong here?

I just can't get this to work despite having watched the video multiple times

KnockKnock.java
/*  So the age old knock knock joke goes like this:
        Person A:  Knock Knock.
        Person B:  Who's there?
        Person A:  Banana
        Person B:  Banana who?
        ...This repeats until Person A answers Orange
        Person A:  Orange
        Person B:  Orange who?
        Person A:  Orange you glad I didn't say Banana again?
*/

//Here is the prompting code
console.printf("Knock Knock.\n");
String who = console.readLine("Who's there?  ");
console.printf("%s who?\n", who);
boolean isInvalidWord = (noun.equalsIgnoreCase("banana");
         do {
         if (InvalidWord); {
         console.printf ("Knock Knock. \n");
            } while(isInvalidWord);
         }

2 Answers

We want to move that prompting code into a do while loop.

Setting up the do-while loop

do {
  // inside the loop
} while (condition);

Wrap the code into a do while and check in the condition to see if who equals "banana" so the loop continues.

do {
  console.printf("Knock Knock.\n");
  String who = console.readLine("Who's there?  ");
  console.printf("%s who?\n", who);
} while (who.equalsIgnoreCase("banana"));

Remember to move your who declaration outside the do block.

String who;
do {
  console.printf("Knock Knock.\n");
  who = console.readLine("Who's there?  ");
  console.printf("%s who?\n", who);
} while (who.equalsIgnoreCase("banana"));
Spencer Eldred
Spencer Eldred
20,271 Points

You need to move more of your code inside the do loop. Your boolean variable 'isInvalidWord' never gets a chance to change. It will either loop continuously or never. It is good to initialize the loop value to true at the beginning, so it loops. Then change the loop value to false based on some user input to break the loop. Hope that helps.