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
Matthew Francis
6,967 PointsNewbie - For each loop and functions
I'm just wondering how to put the value of the method, "test", into the for each loop. This is the nonfunctional code:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
String test() {
String var = "Iloveyou";
return var;
}
for (char letters:test().toCharArray()) {
System.out.println(letters);
}
}
}
1 Answer
Kyle Baker
8,211 PointsTry taking the "test" method out of the "main" method (but still in class HelloWorld), add "public" before "String" for the "test" method, create an object in your "main" method (ex. HelloWorld obj = new HelloWorld();), then use dot notation to call "test()" on the object you created for the "in" part of your for loop (char letters: obj.test().toCharArray()).
To my understanding, you create objects of the class so you can use the methods in that class.