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 trialHeather Gray
6,225 PointsCast as blogpost?
No idea why this isn't working for task 2. Tried multiple strange things. I think this should work, but it's obviously wrong.
import com.example.BlogPost;
public class TypeCastChecker {
/***************
I have provided 2 hints for this challenge.
Change `false` to `true` in one line below, then click the "Check work" button to see the hint.
NOTE: You must set all the hints to false to complete the exercise.
****************/
public static boolean HINT_1_ENABLED = false;
public static boolean HINT_2_ENABLED = false;
public static String getTitleFromObject(Object obj) {
if(obj instanceof String)
return (String) obj;
if(obj instanceof BlogPost)
return (BlogPost) obj;
String result = "";
return result;
}
}
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsHi Heather, There are a some syntax and structural issues with the code.
- The if blocks need to be wrapped in curly braces
{}
- The getTitleFromObject method returns a String. In the second if, can't return type BlogPost as String. Need to recast
obj
toBlogPost
first, then call thegetTitle()
method and return the String result
I've left the last statement for you to complete.
public class TypeCastChecker {
/***************
I have provided 2 hints for this challenge.
Change `false` to `true` in one line below, then click the "Check work" button to see the hint.
NOTE: You must set all the hints to false to complete the exercise.
****************/
public static boolean HINT_1_ENABLED = false;
public static boolean HINT_2_ENABLED = false;
public static String getTitleFromObject(Object obj) {
if (obj instanceof String) { // <-- missing curly braces around 'if' block
return (String) obj;
}
if (obj instanceof BlogPost) { // <-- missing curly braces around 'if' block
// cast obj to BlogPost object
BlogPost post = (BlogPost) obj;
// return post getTitle() results
return // Can you figure out what goes here?
}
String result = "";
return result;
}
}
Post back if still stuck. Good Luck!
Heather Gray
6,225 PointsI did it! Thanks for your help.