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

Code challenge error

I'm having trouble with the challenge. I seem to be stuck can someone please let me know what is wrong with my code?

String who;
do {
// Person A asks:
console.printf("Knock Knock.\n");

// Person B asks and Person A's response is stored in the String who:
  String who = console.readLine("Who's there?  "); 



while (noun.equalsIgnoreCase("banana"));
// Person B responds:
  console.printf("%s who?\n", who); }

THANKS

Hi Steven,

I added markdown to help make the code more readable. If you're curious about how to add markdown like this on your own, checkout this thread on posting code to the forum . Also, there is a link at the bottom called Markdown Cheatsheet that gives a brief overview of how to add markdown to your posts.

Cheers!

1 Answer

Lucas Smith
Lucas Smith
11,616 Points

There are a few quick fixes here.

The first is that you are declaring "who" twice. Once at the top of the code, and once again when you assign it to the input from your console.readLine. All you would need to put there would be

who  = console.readLine("Who's there? ");

Secondly, your while statement should be just OUTSIDE of your do block. This is really just a small syntax issue.

Finally, in your while statement, you are checking the state of the "noun" variable, but you don't have a declared or assigned noun variable. This would need to be changed to your "who" variable.

In summation, it should end up looking more or less like this:

import java.io.Console;

public class knockknock {  //just the class that name that I used in my workspace, not really pertinent

    public static void main(String[] args) {
        Console console = System.console();

String who;
do {
// Person A asks:
console.printf("Knock Knock.\n");

// Person B asks and Person A's response is stored in the String who:
  who = console.readLine("Who's there?  ");   //only assigning "who" here instead of declaring it again



// Person B responds:
  console.printf("%s who?\n", who); }

while (who.equalsIgnoreCase("banana"));  //moved the while statement out of the do block, and changed the variable that it's checking to "who"
    }
}

I hope this helps!

Thanks for the help Lucas!