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 trialNeelesh Tewani
1,239 Pointsplease help me with this challenge i am not able to cross the second task
// in this task i have done this i am not able to find the problem please help me to solve it // String response; do{ response = console.readLine("Do you understand do while loops ?"); if(response.equals("yes")||response.equals("no")){ response = console.readLine("Do you understand do while loops ?"); } }while(response.equals("yes")||response.equals("no")); System.exit(0);
2 Answers
Kevin Faust
15,353 PointsHey Neelesh,
you made it more complicated than necessary. You didn't need any logical operators nor any if statements.
Let's look at this:
String response;
do{
response = console.readLine("Do you understand do while loops ?");
} while(response.equals("No"));
console.printf("Because you said %s, you passed the test!", response);
So you got the first part correct. We create a String variable. What we do next is a do-while loop which you successfully did.
if(response.equals("yes")||response.equals("no")){
response = console.readLine("Do you understand do while loops ?");
}
This part does not make sense. if our response equals yes, then we want to end the loop. You did the same thing in the while loop. Also we didnt need a System.exit because the loop will automatically end if the user enters yes.
So back to the code I posted above. We prompt the user for a response and store it in the response variable. while the response is "No", then we keep looping. If they enter anything else we will let them pass. At the end we write a print statement telling them what they wrote.
Does that make sense?
Kevin
Steven Donovan
13,281 PointsSorry, I wasn't actually referring to the task itself, just the use of equals when comparing to a literal. If the literal is kept to left then you can't get a potential NullPointerException. Nothing to do with actual challenge, just purely Java Best Practice tip.
Kevin Faust
15,353 Pointsah i see. good tip!
Steven Donovan
13,281 PointsSteven Donovan
13,281 PointsHi, best practice is to put the literal first in the above 'equals' calls. If defends against NullPointerException.
Kevin Faust
15,353 PointsKevin Faust
15,353 Pointsthat is wrong. as i said, that line of code should not exist as it is not what the challenge is asking for