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 trialDerek Derek
8,744 PointsI don't know how to pass this task..
Below is what I have, and I am getting compile time errors, telling me that obj is not a String (error at the line after the if statement). Also, why does it error there if obj is not String since it would not satisfy the if condition and therefore should go to the else..?
public static String getTitleFromObject(Object obj) { // Fix this result variable to be the correct string. if (obj instanceof String) { String result = obj; return result; } else { return (String) obj; }
}
2 Answers
Grigorij Schleifer
10,365 PointsHi Hyun,
see here:
https://teamtreehouse.com/community/casting-blogpost
Kevin gives there a great explanation regarding the challenge :)
Happy coding
Grigorij
Evan Demaris
64,262 PointsHello Hyun,
It looks like you aren't casting result
to be a String in your if
, and I'm not certain why you've got an else statement there if you're on the first Challenge; if this is meant to be for part 2 of the Challenge as well, you'd want to cast obj
to the BlogPost type, then get the title from it. I've included working code below; if you use my code directly for the Challenge, you'd need to remove the extraneous result variable and return statement that are in the Challenge by default.
if (obj instanceof String) {return (String) obj;} else {return ((BlogPost) obj).getTitle();}
Please let me know if you need any clarification on how or why my code works!
Grigorij Schleifer
10,365 PointsGrigorij Schleifer
10,365 PointsI commented TASK 1 a little bit ...