I wanted to implement a method which receives as parameters an array with elements of type String
and a value of type String
. The method concatenates the elements of the array with the symbol passed as the second parameter. The problem is that I don't quite understand the return in the methods
public static String concatenando(String[] array, String valor) {
for (int i = 0; i < array.length; i++) {
String concatenacion = array[i] + valor;
}/* Si retorno el valor antes de cerrar el bucle me salta un error porque
el método necesita retorna algo*/
return concatenacion; // Si retorno aquí la variable concatenacion no existe
}
public static void main (String[] args) {
String[] words = {"Uso", "Array", "Java"};
System.out.println(concatenando(words,"-")); // "Uso-Array-Java"
}
I would do it in the following way:
You could also do it using the join method of the String class:
If you return inside the loop you wouldn't even give the loop time to complete. Sometimes that's fine but in your case it's not. In addition to that you must indicate some return value outside the loop also since it could be the case that it does not even enter the loop.
If you return outside the loop you must declare the variable outside the loop as well, otherwise the compiler will throw you an error because you have not declared the variable correctly.
Try this: