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 trialbill curry
Front End Web Development Techdegree Student 7,841 PointsWhy does this code not work if my 'missing person' is entered last?
My while loop works fine if i enter a student not in the database (non-student) and hit 'quit'. (I get my sorry message)
It also works if i enter a non-student name followed by a student name (I get the sorry message followed by the existing student's info.)
However, if i enter the student followed by the non-student, it only shows the existing student's info BUT no sorry message.
Can any help me amend this code so it works both ways(or suggest a cleaner approach)? Thanks
while (true) {
search = prompt("Search student records: Type a name[Jody] or (type 'quit' to end)");
if (search.toLowerCase() === 'quit' || search === null) {
break;
}
for (var i = 0; i < students.length; i++) {
student = students[i];
if (student.name.toLowerCase() === search) {
message += getStudentReport(student);
print(message);
}
}
if (message === '') {
message = 'Sorry, ' + search + ' is not in class';
print(message);
}
}
1 Answer
Steven Parker
231,269 PointsYou're accumulating "message" and checking to see if it is empty to generate the "sorry" response. So when any data has been previously found a "miss" is not detected.
One way to fix this is by setting a boolean before each search, changing it's value on a find, and then after the search loop testing it instead of the contents of "message".