So I'm supposed to write a method to print the elements of an array. This is how I did it:
public static void join(String phrase[])
{
for (int i = 0; i < phrase.length; i++)
{
System.out.print(phrase[i] + " ");
}
}
This code works, but the prof says we must return a String with this method, and I don't know how to do it this way. I tried:
public static String join(String phrase[])
{
for (int i = 0; i < phrase.length; i++)
{
String sentence = System.out.print(phrase[i] + " ");
return sentence;
}
}
Error: incompatible types: void cannot be converted to java.lang.String
I know I cannot use .print because the method is not void. But then, how do I print?
Any ideas? This is a beginner Java class, so I don't know any other way.
String) PS:return String.join(" ", phrase);will be the same as your loop.