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 While Loops

Why do we have to express anyQuestion again?

Right at the beginning of the video we have set, that the String anyQuestion has to put out a question asking "Are there any questions?". -> String anyQuestion = console.readLine("Are there any questions? ");

Later on while doing the while loop it occurs again:

while(anyQuestion.equals("yes")) { String question = console.readLine("What is your question? "); console.printf("I do not understand: %s", question); anyQuestion = console.readLine("Are there any questions? "); }

Why do we have to write out the whole thing? Following my logic, just simply anyQuestion; should be enough in that line since we already have expressed the meaning of the anyQuestion string. I am very new to java and coding overall, probably I do not even get the terminology right, but I am trying my best :)

1 Answer

andren
andren
28,558 Points

Following my logic, just simply anyQuestion; should be enough in that line since we already have expressed the meaning of the anyQuestion string.

I think I can understand more or less why you would think that, but your logic is based on a misunderstanding of how Java and most other OOP (Object Oriented Programming) languages work.

anyQuestion is defined as a String variable, a String is a datatype used to store pure text, when you call the console.readLine() function it returns the answer the user provided as a String.

So in other words in this line:

String anyQuestion = console.readLine("Are there any questions? ");

You are not setting the variable equal to the console.readLine()method call itself, but to the value that calling that method returns.

So if you enter No for example Java would essentially treat that line as:

String anyQuestion = "No";

So to answer your question more directly, anyQuestion is not setup as a method call like you seem to think, it is setup as a pure String, one which ends up storing whatever the user typed when the method was first called. That's why you need to enter the method call each time you want to set it equal to a new user input value.

Wow, thank you so much for the fast reply! This was exactly what I wanted to know. :)