I want to make my class return a value but I want that value to change based like the loop. I think my code will explain it better than I can.
public static String readChat(String value) throws Exception
{
FormatS FormatS = new FormatS();
BufferedReader mainChat = new BufferedReader(new FileReader("./chat.txt"));
String str;
while ((str = mainChat.readLine()) != null)
{
String msg = FormatS.FormatS(str, value);
}
mainChat.close();
return (msg);
Unfortunately that will only return the last one since the loop isn’t returned but only the last message in the loop, How can I make it return every value in the loop as a seperate return? (If possible from here without affecting the other classes)
You can’t. A Java method only returns one value, it can’t return several times.
After the return statement, you’re out of that method!
You can use a Collection (like a List, for instance), to store all your messages, and then return the list.
http://download.oracle.com/javase/6/docs/api/java/util/Collection.html
Check here for additional information on collections. If you’re new to Java and plan on sticking with it, it’s a pretty crucial aspect to master :).
What you should do is instantiate a new Collection, for instance:
and then inside your loop, you’ll do…
And for the gran finale, of course…
In the “outside” method (the caller), you can interate over the list, and use the messages for your needs.