2

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.

4
  • Change the return type from void to String. I believe something is wrong with your logic as well each time you will just return the first element of the array Commented Feb 22, 2018 at 14:22
  • 2
    You don't return a value in each cases, if your array is empty, the loop will not be executed at all, so no return mean return void. The return should be after the loops (and you should concatenate those String) PS: return String.join(" ", phrase); will be the same as your loop. Commented Feb 22, 2018 at 14:22
  • You cannot asing value from System.out.print(), as the error sais, it returns void Commented Feb 22, 2018 at 14:25
  • Check my step by step answer, I believe I don't forget anything in there but can add if something is not clear. Commented Feb 22, 2018 at 14:40

4 Answers 4

2

This would also work:

public static String join(String phrase[])
  {
    String sentence = "";
    for (int i = 0; i < phrase.length; i++)
    {
      sentence += phrase[i] + " ";
    }
    return sentence;
  }

Here is what I'm doing:

1) Creating an empty string outside the for loop that will be used to hold all the values of the array

2) Adding each element of array (with a space after) to the string with sentence += phrase[i] + " ";

3) Once the for loop adds all the elements to the string, return it!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! But what does "sentence +=" means?
All sentence += does is take whatever sentence is and adds a new string to it. So if sentence = "Apple" and you added a line sentence += "Banana", sentence now equals AppleBanana. Hope that helps.
1
  1. System.out.println return void

You can't assign void to a String variable. You simply want to assign the concatenated value, not print it.

String sentence = phrase[i] + " "
  1. You declare sentence each iteration

You need to concatenate each cells, so declare a variable before the loop and append the String in the loop

String sentence = "";
for (int i = 0; i < phrase.length; i++){
    sentence +=  phrase[i] + " "; //same as sentence = sentence + phrase[i] + " ";
    return sentence;
}
  1. You return a value inside the loop...

The loop will end at the return, so only the first value will be present in the String. Only return the value after it is fully done, after the loop.

String sentence = "";
for (int i = 0; i < phrase.length; i++){
    sentence +=  phrase[i] + " ";
}
return sentence;

FYI: In the same issues, if the array is empty, no value are returned, so it will also be a problem since a method should return a String in every cases (or throw an exception`.

Shorter solution :

This loop can be done simply with String.join since Java 8

return String.join(" ", phrase);

Comments

1

Please do the following:

public static String join(String phrase[]){
    StringBuilder str = new StringBuilder();
    for(String s: phrase){
        str.append(s);
    }
    System.out.println(str);
    return str.toString();
  }

Dont use += and add the values of the string array to another string as it will create a new object every time you add a new string to the preprocessed string. Instead use StringBuilder which is more memory efficient.

You can also do the following:

public static String join(String phrase[]){
    String str = Arrays.toString(phrase);
    System.out.println(str);
    return str;
}

1 Comment

Do know you that String.join(String delimiter, String[] value) is a thing ? And it support a delimiter to be even more efficient.
0

This will print each elements and return the entire result :

public static String printElements(String phrase[]) {
    String result = "";
    for (int i = 0; i < phrase.length; i++)
    {
        System.out.print(phrase[i] + " ");
        result += phrase[i];     
        if( i != phrase.length - 1)
        {
            result += " ";
        }

    }
        return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.